【发布时间】:2022-01-21 11:45:52
【问题描述】:
我有一类(子)对象
public class SubObjects {
int depth;
public SubObjects(int d) {
this.depth = d;
}
}
还有一类对象
public class Objects {
private int height;
private int width;
ArrayList<SubObjects> liste;
public Objects(int h, int w) {
this.height = h;
this.width = w;
this.liste = new ArrayList<>();
}
}
对象包含值高度和宽度以及子对象的 ArrayList。这可以按预期工作,但是我确实想在这些 ArrayList 中存储来自不同类的多种类型的子对象。
经过一番谷歌搜索后,我将 Objects 类更改为
public class Objects {
private int height;
private int width;
ArrayList<Object> liste;
public Objects(int h, int w) {
this.height = h;
this.width = w;
this.liste = new ArrayList<Object>();
}
}
这允许我按照我的意图将来自第二类 SubObjects2 的对象存储在 ArrayList 中
public class SubObjects2 {
int weight;
public SubObjects2(int weight) {
this.weight = weight;
}
}
这太棒了,我以为我已经解决了它,但后来我运行了主类,而我用早期的实现可以从 ArrayList 中的对象中返回带有 getter 的值
... liste.get(i).depth (in a for loop)
同样的查询现在返回以下错误
Unresolved compilation problem:
depth cannot be resolved or is not a field
我现在如何访问存储在 ArrayList 中的子对象内的值?
【问题讨论】:
-
用
public int depth代替int depth -
对象和子对象有什么区别?为什么他们有s?它们是东西的集合吗?还是一件事? SubObject 与 Object 有关系吗?也许你的意思是让 SubObject 扩展 Object?对象是由其他对象还是子对象组成的?