我是一个初学者,并尝试访问子类中对象数组的实例变量,但我得到的只是初始化值而不是更新值。它有点复杂,但是简单,代码就可以这样。
Seed.java
public class Seed {
int weight = 0;
}
Apple.java
public class Apple {
public Seed[] seed = new Seed[10];
}
MainActivity.java
Main Activity {
public static Apple[] apple = new Apple[2];
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
apple[0] = new Apple();
for (int i = 0; i < 10; i++)
apple[0].seed[i] = new seed();
assign();
//and here new activity childActivity starts
}
public void assign() {
for(int i =0; i < 10; i++)
apple[0].seed[i].weight = 10;
}
}
ChildActivity.java
ChildActivity extends mainActivity {
//display a layout with a button
//upon button click
display();
public void display() {
//output to textview
String.valueOf(apple[0].seed[0].weight);
}
给出0而不是10的输出。我无法弄清楚什么是错的。我检查了mainActivity中正确分配的值。我没有错误或崩溃。谢谢你的帮助!