專家讀書筆記
這句話怎麼理解
所有代碼都經過測試
java version
Java(TM)
Java HotSpot(TM) Client VM (build
如大家發現任何錯誤
缺省構造函數的問題
class是由class的構造函數constructor產生的
如果父類base class只有缺省構造函數
class base{
}
class derived extends base{
public static void main(String[] args){
derived d=new derived();
}
}
下面我自己顯式地加上了缺省構造函數
class base{
base(){
System
}
}
class derived extends base{
derived(){
System
}
public static void main(String[] args){
derived d=new derived();
}
}
執行結果如下
base constructor
derived constructor
我要說明的問題出在如果base class有多個constructor
而derived class也有多個constructor
class base{
base(){
System
}
base(int i){
System
}
}
class derived extends base{
derived(){
System
}
derived(int i){
System
}
public static void main(String[] args){
derived d=new derived();
derived t=new derived(
}
}
D:
base constructor
derived constructor
base constructor
derived constructor int i
如果將base 類的構造函數注釋掉
class base{
// base(){
// System
// }
base(int i){
System
}
}
class derived extends base{
derived(){
System
}
derived(int i){
System
}
public static void main(String[] args){
derived d=new derived();
derived t=new derived(
}
}
D:
derived
symbol : constructor base ()
location: class base
derived(){
^
derived
symbol : constructor base ()
location: class base
derived(int i){
說明子類中的構造函數找不到顯式寫出的父類中的缺省構造函數
那麼如果你不想子類的構造函數調用你顯式寫出的父類中的缺省構造函數怎麼辦呢?
如下例
class base{
// base(){
// System
// }
base(int i){
System
}
}
class derived extends base{
derived(){
super(
System
}
derived(int i){
super(i);
System
}
public static void main(String[] args){
derived d=new derived();
derived t=new derived(
}
}
D:
base constructor int i
derived constructor
base constructor int i
derived constructor int i
super(i)表示父類的構造函數base(i)請大家注意一個是super(i)一個是super(
結論
From:http://tw.wingwit.com/Article/program/Java/hx/201311/27071.html