[英]constructors in java
public class A {
public A() {
System.out.println("a1");
}
public A(int x) {
System.out.println("a2");
}}
public class B extends A {
public B() {
super(5);
System.out.println("b1");
}
public B(int x) {
this();
System.out.println("b2");
}
public B(int x, int y) {
super(x);
System.out.println("b3");
}}
我不明白為什么當我運行B b= new B();
時不應用A的默認結構B b= new B();
B擴展了A,所以我們首先將A的結構打印為“ a1”,然后將A的第二種結構稱為“ a1”,而B()
打印“ b1”,但是當我運行它時,它只打印“ a2,b1”,因此顯然A()
開始就不會應用A()
-為什么?
當你說B b = new B();
您正在調用默認的構造函數
public B() {
super(5);
System.out.println("b1");
}
由於已經調用了其超級構造函數[ super(5)
],因此編譯器將不會插入隱式默認構造函數。 因此,結果。
注意:從您的問題來看,您似乎具有在創建對象時調用所有構造函數的想法。 恐怕這是不正確的。 只有構造函數將被調用,你顯式調用創建對象。 如果該構造函數通過this()
方法調用其他構造函數,則僅將調用其他構造函數。
這是因為您在B構造函數中調用了super(5),后者調用了第二個A構造函數而不是第一個。
B擴展了A,所以首先我們稱A的結構為“ a1”
這句話是不正確的。 在B類中,您的無參數構造函數
public B() {
super(5);
System.out.println("b1");
}
調用具有int參數的超類(類A)的構造函數。
public A(int x) {
System.out.println("a2");
}
您永遠不會調用super(),因此當您調用B的任何構造函數時,不會調用顯示“ a1”的構造函數
調用超級構造函數必須是構造函數的第一行。 如果要調用超類的無參數構造函數(在本例中為打印“ a1”的構造函數),則應編寫...
public B() {
super();
System.out.println("b1");
}
如果您未指定調用超級構造函數,那么java會自動調用no參數超級構造函數。
我認為您會誤解Java如何處理構造函數。 首先,默認情況下,Java在每個類中僅調用一個構造函數,除非您明確告知它使用this(...)
來調用更多構造函數。 其次,一個被調用的構造是超類的默認構造函數(因此它將調用super()
,而不是this()
); 所以A
類實際上看起來像這樣:
public class A {
public A() {
super(); // implicit call to super(), which is Object()
System.out.println("a1");
}
public A(int x) {
super(); // implicit call to super(), which is Object()
System.out.println("a2");
}
}
因此,調用A()
將隱式調用Object()
,但是調用A(int x)
也將隱式調用Object()
,而不是-似乎是假設的A()
。
由於在B中您始終明確指定要調用另一個構造函數,因此編譯器將不會添加任何內容。 下面我添加了對super(...)
和this(...)
的調用將發生什么的注釋
public class B extends A {
public B() {
super(5); // explicit call to A(5), no implict call to A()
System.out.println("b1");
}
public B(int x) {
this(); // explicit call to B(), no implicit call to A()
System.out.println("b2");
}
public B(int x, int y) {
super(x); // explict call to A(x), no implicit call to A()
System.out.println("b3");
}
}
同樣,要記住的重要一點是,除非您使用this(...)
或super(...)
顯式調用另一個構造函數,否則Java將在任何構造函數的第一行中插入對super()
的調用。 它永遠不會自己插入this()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.