2014-06-27 69 views
-3

如果我們使用super關鍵字來調用子對象中父類的方法,是否會創建父對象?父對象可以使用super創建,以調用父方法

結果顯示Mybase和MySub都有相同的參考地址。不確定它是否是一個好的演示。

類Mybase {

public void address() { 
    System.out.println("super:" + this); 
    System.out.println(this.getClass().getName()); 
} 

}

類MySub延伸Mybase {

public void address() { 
    System.out.println("this:" + this); 
    System.out.println(this.getClass().getName()); 
} 

public void info() { 
    System.out.println("this:" + this); 
    super.address(); 
} 

}

公共類SuperTest {

public static void main(String[] args) { 
    new MySub().info(); 
} 

}

+0

爲什麼你不試試找出答案? – awksp

+0

它創建子類的實例,但它需要初始化父類的成員 –

+0

歡迎來到SO。像這樣的問題非常模糊,可能會吸引downvotes。試着做一小段代碼來說明你的問題! –

回答

0

好吧,讓我們來看看!

您的測試不是相當要回答你的問題。如果您想查看是否創建了一個對象,爲什麼不創建一個構造函數,以便在調用時打印到控制檯?

public class Test { 

    static class Parent { 
     Parent() { 
      System.out.println("Parent constructor called"); 
     } 

     void method() { 
      System.out.println("Parent method called"); 
     } 
    } 

    static class Child extends Parent { 
     Child() { 
      System.out.println("Child constructor called"); 
     } 

     @Override 
     void method() { 
      System.out.println("Child method called"); 
      super.method(); 
     } 
    } 

    public static void main(final String[] args) { 
     new Child().method(); 
    } 
} 

如果你運行它,你會得到這樣的輸出:

Parent constructor called 
Child constructor called 
Child method called 
Parent method called 

所以你可以看到,當method()人如其名,是使用了super關鍵字時,不會創建Parent對象。所以你的問題的答案是「不」。


的原因是因爲supersuper()不同super(無括號)用於訪問父類的成員。 super()(帶圓括號)是對父構造函數的調用,並且在構造函數中僅在構造函數內有效作爲第一個調用。所以使用super(無括號)將不是創建一個新的對象。

此外,super()實際上並不創建新的獨立Parent對象。它只是在子構造函數繼續之前需要的Parent字段的初始化工作。

相關問題