this和Super關鍵字

super()、super.和 this()、this.
1–this:在運行期間,哪個對象在調用this所在的方法,this就代表哪個對象,隱含綁定到當前“這個對象”。

2–super():調用父類無參構造器,一定在子類構造器第一行使用!如果沒有則是默認存在super()的!
這是Java默認添加的super()。

3– super.是訪問父類對象,父類對象的引用,與this.用法一致

4– this():調用本類的其他構造器,按照參數調用構造器,必須在構造器中使用,必須在第一行使用,
this() 與 super() 互斥,不能同時存在

5– this.是訪問當前對象,本類對象的引用,在能區別實例變量和局部變量時,this.可省略,否則一定不能省!

6–如果子父類中出現非私有的同名成員變量時,子類要訪問本類中的變量用this. ;子類要訪問父類中的同名變量用super. 。

eg1:方法參數傳遞原理 與 this關鍵字
public class Demo {
public static void main(String[] args){
Point2 p1=new Point2();
p1.x=10;
p1.y=15;
p1.up(5);
System.out.println(p1.x+”,”+p1.y);//10,10
Point2 p2=new Point2();
p2.up(3);
System.out.println(p2.x+”,”+p2.y);//0,-3
}
}
class Point2{
int x;
int y;
public void up(int dy){
this.y=this.y-dy;
}
}

eg2:this. 和 this()
public class Demo {
public static void main(String[] args){
Cell c = new Cell();
System.out.println(c.x + “,”+c.y);//3,2
}
}
class Cell {
int x; int y;
public Cell() {
this(3,2);//調用本類的其他構造器
}
public Cell( int x, int y) {
this.x = x;
this.y = y;
}
}

eg3:super()
public class Demo {
public static void main(String[] args){
Xoo x=new Xoo(2);//Call Xoo(2)
Xoo x1=new Yoo();//Call Xoo(100)
}
}
class Xoo {
public Xoo(int s) {
System.out.println(“Call Xoo(“+s+”)”);
}
} // super()用於在子類構造器中調用父類的構造器

class Yoo extends Xoo {
// public Yoo() {}//編譯錯誤,子類調用不到父類型無參數構造器
public Yoo() {
// super();//編譯錯誤,子類調用不到父類型無參數構造器,因爲若父類定義了帶參的構造函數,系統就不會幫你生產無參數構造函數。
super(100);//調用了父類 Xoo(int) 構造器
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章