Java入門學習-理解super,this,@override的用法
一、super和this
1、this
指向自己的引用。
我之前一般都在建構函式中用this
class parents{
int x,y;
public parents(int x,int y) {
this.x=x;
this.y=y;
}
}
用法:
this.x 指向當前的x欄位
this.method() 指向當前的method()方法
this() 指向當前構造方法
2、super
呼叫父類的構造欄位用super.x;
呼叫父類的構造方法用super();
呼叫父類方法用super.method();
//接上面程式碼,這時我想繼承parents
public class ThisSuper extends parents {
public ThisSuper() {
}
//這時ThisSuper會報錯:Implicit super constructor parents() is undefined. Must explicitly invoke another constructor
//如果我在Thissuper的構造方法裡,加上super(0,0);報錯就消失了,因為我用super()定義了父類的構造方法。
學習中遇到的細節:
1、我試著把super寫在main方法裡,提示:Cannot use super in a static context。所以super不能放在靜態區域裡。
2、同一個方法內只能呼叫一次this()或super()。否則會報錯:Constructor call must be the first statement in a constructor
其實extends時,就會呼叫super();
二、@override
override是重寫父類非私有的方法,返回型別和形參都不能改變。
然後是,不能重寫final方法(繼承的前提)
重寫方法不能丟擲新的檢查異常或者比被重寫方法申明更加寬泛的異常。
上面這句話我理解是,父類方法已定義好了範圍,子類重寫他就必須在他範圍內寫,所以,父類定義了異常,子類就不能丟擲更大的異常。
總而言之,重寫是具體做什麼時的重寫,然後範圍只能寫小不能寫大。
下面還是舉個栗子:
class parents {
public int add(int a,int b){
return (a+b);
}
}
public class ThisSuper extends parents {
@Override
public int add(int a,int b){
int c=a*10+b*10;
return c;
}
public static void main(String[] args) {
ThisSuper t=new ThisSuper();
parents p=new parents();
parents pt=new ThisSuper();
System.out.println("重寫後的方法:a*10+b*10="+t.add(3,4));
System.out.println("父類方法:a+b="+p.add(3,4));
System.out.println("父類型別但是用子類方法實現:add(3, 4)="+pt.add(3,4));
//輸出:
/*
重寫後的方法:a*10+b*10=70
父類方法:a+b=7
父類型別但是用子類方法實現:add(3,4)=70
*/
//第三條是因為父類也有這個方法,所以可以實現。
//如果父類沒有這個方法,使用parents pt=new ThisSuper();就會報錯The method te() is undefined for the type parents
}
}
實踐時,犯了個傻乎乎的錯誤:打算重寫父類建構函式。其實重寫是在繼承類後,方法之間的事情。然後建構函式是用來呼叫初始化的。前面也說了不用super,子類也會預設呼叫父類的建構函式。即無繼承何來重寫。
寫最後一個例子的時候,想起了咦,我繼承了怎麼沒有報錯。前面寫到
如果我在Thissuper的構造方法裡,加上super(0,0);報錯就消失了,因為我用super()定義了父類的構造方法。
再看一遍,想起來是因為父類是過載帶引數的構造方法,我繼承他。原因是系統會呼叫的是預設的無引數方法,但是因為我寫了有引數的構造方法,系統不會預設生成無引數構造方法,所以才報錯。
然後我除了用super(0,0);還可以在父類方法寫上了無引數的構造方法。