[英]Java | acessing object variables from inside constructor?
我通常不使用 Java,我目前正在尝试帮助朋友完成 Java 作业,这让我陷入困境
我正在尝试访问我在对象的构造函数中创建的数组,但我不知道如何访问它。
public class ADTbag {
String item = "Testing";
public ADTbag(int size) {
// This constructor has one parameter, name.
String[] bag = new String[size];
bag[0] = Integer.toString(size);
System.out.println("A bag was created with the size of " + size + " | " + bag[0]);
}
public void insert() {
/* Insert an item */
/* One Problem this public void doesn't have access to the bag var"
System.out.println(bag);
}
我觉得这是 Java 中的一个简单概念,但我在谷歌上找不到任何对我有帮助的东西。 我希望能够使用 insert 方法在包或字符串数组对象中插入一些东西。 所以像这样的事情。
public static void main(String []args) {
/* Object creation */
ADTbag myBag = new ADTbag(5);
String value = "Some Value";
/* I want to do this */
mybag.insert(value);
}
}
您需要使bag
成为类成员,以便可以在构造函数外部访问它。
将变量定义为实例变量
public class ADTbag {
String item = "Testing";
String[] bag;
public ADTbag(int size) {
// This constructor has one parameter, name.
this.bag = new String[size];
bag[0] = Integer.toString(size);
System.okaut.println("A bag was created with the size of " + size + " | " + bag[0]);
}
public void insert() {
/* Insert an item */
/* One Problem this public void doesn't have access to the bag var"
System.out.println(bag);*/
}
}
上面看起来像。
首先,您必须使手袋领域变得全球化。 之后,我们可以创建一个函数来向您的包中添加/添加新元素。 然后,就不必像您正在尝试的那样使用构造函数。
另一件事是,当您谈论将itens插入和/或添加到“列表”时,使用ArrayList
代替标准array
。
ArrayList是一个数据/集合结构,使您可以在运行时在同一对象上方添加,删除,设置,获取(以及其他一些操作)。 如果要在数组中插入新项,就不能; 为此,我们必须创建另一个具有size + 1的数组,并在设置新数组的所有元素之后。 那么,这对于一个简单的操作来说很混乱。
考虑到这一点,我将为您提供一种使用此方法的方法,请看一下:
import java.util.ArrayList;
public class ADTbag {
/*
global field to be referenced through entire class.
We have to specify the type of objects that will be inserted
inside this list, in this case String
*/
ArrayList<String> bag;
String item = "Testing";
//constructor doesn't need parameter
public ADTbag() {
//here we init the bag list
bag = new ArrayList();
//adds your "standard item" on creating
bag.add(item);
/*
prints your msg.
- to get the size of a ArrayList just call list.size();
- to get the item from the X index just call list.get(X)
*/
System.out.println("A bag was created with the size of " + bag.size() + " | " + bag.get(0));
}
/*
you doesn't need a new method
*/
}
要使用此功能:
public static void main(String[] args) {
ADTbag myBag = new ADTbag();
myBag.bag.add("some value");
}
您可以在方法外部将bag声明为类,然后在构造函数中为其分配一个新的String。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.