我正在尝试创建一种可以查看对象的方法。如何通过bag1
方法访问view()
对象?
public class ArrayBagUtilities {
public void Create() {
Scanner keyboard = new Scanner(System.in);
System.out.print("Size of bag 1: ");
int size = keyboard.nextInt();
Bag bag1 = new ArrayBag(size);
keyboard.nextLine();
String itemStr;
for (int i = 0; i < size; i++) {
int n = i+1;
System.out.print("Item " + n + ": ");
itemStr = keyboard.nextLine();
bag1.add(itemStr);
}
}
public void view() {
System.out.print(bag1);
}
}
答案 0 :(得分:2)
您可以将bag1声明为类的属性。
public class ArrayBagUtilities {
private Bag bag1;
....
public void Create() {
....
bag1 = new ArrayBag(size);
....
}
public void view() {
System.out.print(bag1);
}
}