【发布时间】:2020-09-11 14:28:27
【问题描述】:
我有一个父子类定义如下:
public class Parent {
public int values_ = 0;
public void setValue(int v)
{
this.values_ = v;
}
}
还有一个子类如下
public class Child extends Parent {
public double key = 3;
}
我想要一个子列表,其中子列表中的每个子都将具有父列表中每个父对象的属性。
我尝试过这样的事情:
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Parent> parentList = new ArrayList<Parent>();
Parent p1 = new Parent();
p1.setValue(10);
parentList.add(p1);
Parent p2 = new Parent();
p1.setValue(20);
parentList.add(p2);
ArrayList<Child> childrenList = new ArrayList<Child>();
for(Parent p : parentList)
{
Child c = new Child();
System.out.println(c.values_);
System.out.println(c.key);
childrenList.add(c);
}
}
}
但它不起作用。我的孩子仍然有来自父母的默认值,而不是设置的值
我该怎么办?
【问题讨论】:
-
在最后一个
for循环中,您永远不会使用Parent p变量。您如何期望c具有您未从p传递的值? -
@LuiggiMendoza 我想将 p 作为孩子,但它也不起作用
-
您这样做的具体目的是什么?除非 p 是 Child,否则您不能将 p 转换为 Child。
-
我要做的是从我作为输入接收的父对象列表中构建子对象列表。我想要做的是将每个父级的属性保留在父级列表中,但为每个子级添加新属性
-
你可能需要在
Child类中实现一个拷贝构造函数:Child(Parent p) { this.setValue(p.getValue());}
标签: java inheritance arraylist derived-class