从今天开始, Thinking In Java的习题我会尽量都做一遍. 以加深印象.
/**
* Exercise 5: (1) Create two classes, A and B,* with default constructors (empty argument lists)
* that announce themselves. Inherit a new class called C from A,
* and create a member of class B inside C.
* Do not create a constructor for C. Create an object of class C
* and observe the results.
*/
package reusing;
class Are{
Are(){
System.out.println("Constructor of Are.");
}
};
class B{
B(){
System.out.println("Constructor of B.");
}
}
public class C extends Are{
private B b=new B();
/*
* 如果没有C(), 程序会调用C的父类A的constructor.
* 执行结果是 ...Are, ...B
* 有了C(),
* 执行结果是 ...B, ...C
*/
/*
C(){
System.out.println("Constructor of C.");
}
*/
public static void main(String[] args) {
//执行后还是会调用Are的Constructor
C c=new C();
}
}