如果子類構(gòu)造函數(shù)里沒有super,系統(tǒng)默認(rèn)super(),
順序是:先父類,后子類,對(duì)于每個(gè)類,都是先初始化,在調(diào)用構(gòu)造方法
“父類的構(gòu)造方法調(diào)用發(fā)生在子類的變量初始化之前”??梢杂孟旅娴睦觼碜C明:
例一
// Petstore.java
class Animal {
Animal() {
System.out.println("Animal");
}
}
class Cat extends Animal {
Cat() {
System.out.println("Cat");
}
}
class Store {
Store() {
System.out.println("Store");
}
}
public class Petstore extends Store{
Cat cat = new Cat();
Petstore() {
System.out.println("Petstore");
}
public static void main(String[] args) {
new Petstore();
}
}
運(yùn)行這段代碼,它的執(zhí)行結(jié)果如下:
Store
Animal
Cat
Petstore
例二
class C {
C() {
System.out.print("C");
}
}
class D {
D() {
System.out.print("D");
}
}
class A {
C c = new C();
A() {
this("A");
System.out.print("A");
}
A(String s) {
System.out.print(s);
}
}
public class B extends A {
D d= new D();
B() {
// super("A->B");
System.out.print("B");
}
public static void main(String[] args) {
new B();
}
}
打印是CAADB
$處若執(zhí)行的話打印是CA->BDB
本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)
點(diǎn)擊舉報(bào)。