我使用多态数组创建了一个基本的继承程序。从父类开始,循环遍历该数组,并且每个索引处的每个对象(从子类创建)执行父类的实例方法。
作为一个实验,我在其父类类型的子类构造函数中创建了一个对象,并从那里执行父类的实例方法。
由于我不知道的原因,这导致实例方法(从子类的构造函数执行)执行的次数作为父类的多态数组的长度(如果多态数组有5 个元素,则子-class' 方法调用将被执行5次)。
这是父类:
public class MyClass
{
// instance variables
protected String name;
protected String numStrings;
// constructor
public MyClass(String name)
{
this.name = name;
}
// instance method
public void getDescription()
{
System.out.println("The " + name + " has " + numStrings + " strings.");
}
// main method
public static void main(String[] args)
{
MyClass[] instruments = new MyClass[2];
instruments[0] = new Child("Ibanez bass guitar");
instruments[1] = new Child("Warwick fretless bass guitar");
for(int i = 0, len = instruments.length; i < len; i++)
{
instruments[i].getDescription();
}
} // end of main method
} // end of class MyClass
...这是子类:
public class Child extends MyClass
{
// constructor
public Child(String name)
{
super(name); // calling the parent-class' constructor
super.numStrings = "four";
MyClass obj = new MyClass("asdf");
obj.getDescription();
}
} // end of class Child
...这是输出:
The asdf has null strings.
The asdf has null strings.
The Ibanez bass guitar has four strings.
The Warwick fretless bass guitar has four strings.