父类数组是否可以在Java中保存子类对象?

时间:2016-05-28 10:07:08

标签: java

我有一个名为Student的父类。我通过扩展这个创建了两个子类PermanentStudent和CasualStudent。我已经为扩展子类编写了构造函数(两个子类都有自己的构造函数)。现在,我正在制作一个10个学生的阵列,其中4个将是永久学生,6个将是CasualStudents。为此,我做了如下:

Student[] a = new Student[10];
int count;

现在,我希望通过构造函数向4个永久学生对象和6个临时学生对象填充数据。我做了以下,

for (count = 0; count < 4; count++)
{
    a[count] = new PermanentStudent(a,b,c); // invoking the constructor
}
for (count = 4; count < 10; count++)
{
    a[count] = new CasualStudent(x,y); // invoking the constructor of the other class
}

但这给了我一个编译错误。我在哪里错了?谢谢!

2 个答案:

答案 0 :(得分:1)

您的案例中的Base base = new Sub()base[i] = new Sub()分配在Java中是合法的。 问题出在你的构造函数中,检查Student中是否存在无参数构造函数。

答案 1 :(得分:0)

如上所述,这是构造函数的问题,而不是多态本身(当我测试它时它会起作用吗?)。可能检查一下你的构造函数数据类型是否匹配,并且没有构造函数可以在你的超类中初始化