我已創建使用多態性陣列的基本程序的繼承。在父類中,此數組循環遍歷,並且每個索引處的每個對象(從子類創建)都執行父類的實例方法。
作爲一個實驗中,我創建父類型子級其的構造方法中的一個對象,並從那裏執行父級實例方法。
對於我的原因未知,這是造成實例方法(從子級執行構造函數)來執行的次數作爲父級的長度多態性陣列 (如果多態陣列具有元素,則將執行子類的方法調用)。
這是什麼奇怪的繼承循環?
這裏是父類:
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.
這裏沒有繼承循環。 'MyClass obj'似乎比有用的更混亂,所以我會刪除它。 –
請記住,輸出流(System.out,System.err)不同步,所以輸出的順序是偶然的。 –
感謝@MarcinSanecki,這很有趣......那麼他們是按照處理時間的順序執行的呢?什麼可能是更好的替代測試? –