声明父类引用类型数组,然后为元素分配子类实例。步骤:声明父类引用类型数组。分配数组大小。使用 new 运算符为元素分配子类的实例。

如何生成 Java 中的父类对象数组
方法:
使用父类的引用类型声明数组,然后为数组元素分配子类的实例。
详细步骤:
立即学习“Java免费学习笔记(深入)”;
-
声明父类引用类型数组:
ParentClass[] parentArray;
其中
ParentClass是父类的名称。 -
分配数组大小:
parentArray = new ParentClass[size];
其中
size是所需的数组大小。 -
为数组元素分配子类实例:
使用new运算符为数组元素分配子类的实例。例如,要为ChildClass子类分配一个实例,请使用以下语法:parentArray[index] = new ChildClass();
其中
index是数组中元素的索引。
代码示例:
public class Example {
public static void main(String[] args) {
// 声明一个引用父类 Person 的数组
Person[] people = new Person[2];
// 分配子类实例(Student 和 Employee)给数组元素
people[0] = new Student();
people[1] = new Employee();
// 通过父类引用访问子类方法
people[0].introduce(); // 调用 Student 类中的 introduce() 方法
people[1].introduce(); // 调用 Employee 类中的 introduce() 方法
}
// 父类 Person
static class Person {
public void introduce() {
System.out.println("I'm a person.");
}
}
// 子类 Student
static class Student extends Person {
@Override
public void introduce() {
System.out.println("I'm a student.");
}
}
// 子类 Employee
static class Employee extends Person {
@Override
public void introduce() {
System.out.println("I'm an employee.");
}
}
}











