糯米文學吧

位置:首頁 > 計算機 > java語言

Java程式設計中this關鍵字與super關鍵字的使用方法

java語言5.11K

this

Java程式設計中this關鍵字與super關鍵字的使用方法

總要有個事物來代表類的當前物件,就像C++中的this指標一樣,Java中的this關鍵字就是代表當前物件的引用。

它有三個主要的作用:

1、在構造方法中呼叫其他構造方法。

比如有一個Student類,有三個建構函式,某一個建構函式中呼叫另外建構函式,就要用到this(),而直接使用Student()是不可以的。

2、返回當前物件的引用。

3、區分成員變數名和引數名。

看下面的例子

public class Student { private String name; private int age; private String college; public Student() { age = 20; } public Student(String name) { this();//can not be call Student,only use this() method. = name; tln("this student name is "+name); } public Student(String name,String college) { this(name);//C++中可以直接用Student(name)呼叫其他建構函式 ege = college; tln("this student name is "+name+" college is "+college); } public Student upgrade() { age++; return this; } public void print() { tln("name is: "+name +" age is: "+age +" college is: "+college); } public static void main(String[] args) { Student student1 = new Student("linc"); Student student2 = new Student("linc","shenyang college"); ade()t(); } }

迷失在茫茫的物件海洋時,不要忘了用this來找到自我。

super

super是this的父輩。從面相物件的角度說,這兩個概念是很好理解的。

子類從父類繼承過來,父類的protected及以上的'屬性和方法在子類中是天生就具有的。那麼,為什麼還要有super這個關鍵字?

第一、看父類的構造

子類構造時要先呼叫父類的預設建構函式的,這與C++的構造屬性一致。當父類有多個建構函式時,你需要指定呼叫哪個。這是就需要使用super(arg1,arg2...)。

需要注意的是,在子類的建構函式中呼叫基類的建構函式時,必須要把super寫作最前面,否則報錯。

第二,在子類覆蓋父類的一些方法中再呼叫父類的此方法。大家都知道,在子類中覆蓋父類的一些方法是面向物件中多型的一種方式,而因為其他種種原因,需要在此方法中呼叫父類的此方法,用以區分,此時需要使用super來完成。

public class ClassLeader extends Student { private String duty; public ClassLeader() { duty = "class monitor"; } public ClassLeader(String duty,String name,String college) { super(name,college); = duty; } public void print() { t(); tln("duty is " + duty); } public static void main(String[] args) { ClassLeader leader = new ClassLeader("life","linc","shenyang"); t(); } }

將兩個類檔案放在同一個目錄,編譯並執行:

D:workspaceJavaproject261super>javac -d . *java D:workspaceJavaproject261super>java ClassLeader

執行結果:

this student name is linc this student name is linc college is shenyang name is: linc age is: 20 college is: shenyang duty is life

看看在其他語言中是怎樣來處理的:

C#中提供了base關鍵字來完成super相似的功能,C++直接用基類的名字來呼叫。