試圖瞭解super()方法何時調用。在下面的代碼中,Child類有一個沒有參數的構造函數,所以編譯器不能插入super()。那麼如何調用父構造函數。當super()在下面的代碼中調用時
public class Parent
{
public Parent()
{
System.out.println("In parent constructor");
}
}
public class Child extends Parent
{
private int age;
public Child()
{
this(10);
System.out.println("In child constructor with no argument");
}
public Child(int age)
{
this.age = age;
System.out.println("In child constructor with argument");
}
public static void main(String[] args)
{
System.out.println("In main method");
Child child = new Child();
}
}
輸出:
In main method
In parent constructor
In child constructor with argument
In child constructor with no argument
this(10)只能用於調用當前的類(Child)構造函數。 – Bikku
你能否在調試模式下運行你的程序?它會幫助你理解輸出。 – Bikku