我使用多态数组创建了一个基本的继承程序。从父类中,这个数组循环通过,每个索引处的每个对象(从子类创建)执行父类的实例方法。
作为一个实验,我在子类中创建了一个对象,它的父类类型的构造函数,然后从那里执行父类实例方法。
因为我不知道的原因,这导致实例方法(从子类‘构造函数中执行)以父类’多态数组的长度执行次数(如果多态数组具有5元素,则子类的方法调用将执行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...here是儿童班:
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...and这里是输出:
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.发布于 2012-09-12 07:57:53
有问题的是:
MyClass obj = new MyClass("asdf");如果您只是简单地调用getDescription()而不是obj.getDescription(),那么应该没有问题。由于'MyClass‘扩展了’new MyClass("...")‘,超级构造函数调用用于初始化超类中的所有内容(假设您现在可以将其想象为隐式new MyClass("...")),因此不必显式实例化'MyClass’。
发布于 2012-09-12 08:03:39
任何地方都没有奇怪的继承循环。创建两个子实例,每个实例执行以下代码
MyClass obj = new MyClass("asdf");
obj.getDescription();并按预期打印“asdf有空字符串”。请注意,obj已经为垃圾收集做好了准备,因为在执行这段代码之后,它不再是可访问的。也就是说,这两行是不必要的,它们唯一的效果就是输出“asdf有空字符串”。当您编写超级(“某事”)时,已经调用了超类的构造函数。
然后,两个子对象最终被打印出来,并带有正确的值。
https://stackoverflow.com/questions/12383552
复制相似问题