1. 程式人生 > >java中關鍵字 this 和super的作用及用法

java中關鍵字 this 和super的作用及用法

this關鍵字1)在類的內部代表物件本身,你應該看到過this.xxx(),this.xxx這種用法吧,this就代表這個類的物件,比如public class A { private String name; public void setName(String name) { //this就代表A的一個物件 //當你例項一個A時,A a1 = new A();this就是那個a1,只是this在內部用,而a1在外部用 //A a2 = new A()同理,這時在a2的內部,this就代表a2 this.name = name; }}2)this的第二種用法,是用在建構函式裡的當在構造器裡要呼叫自己的其他構造器時,就用thisthis必須放在第一行public class A { private String name; public A() { this("no name"); } public A(String name) { this.name = name; //other codes }}super關鍵字1)顯式的呼叫父類的方法當從一個類繼承時,子類和父類都有一個同名方法,也就是子類覆蓋了父類的方法,可是又想呼叫父類的方法,那麼就要用super,像繼承swing的類時就有個好例子public class MyPanel extends JPanel { @Override public void paint(Graphics g) { super.paint(g);//如果不用super,那麼就會呼叫自己的paint方法 }}2)用在構造器,和this的用法一樣,super也可以用在構造器,this是呼叫自己的其他構造器,那麼super當然就是呼叫父類的構造器了 -------------------------------------------------------super和this用在構造器的話,前者表示呼叫父類的夠造器,後者表示呼叫本類的其他構造器,他們兩個都必須是寫在構造器裡的第一行public class Person { private String name; private int age; public Person() { name = ""; age = 0; } public Person(String n, int a) { name = n; age = a; }}public class Student extends Person { private String id;//學號 public Student(String name, int age) { super(name, age);//必須寫在第一行,子類無法直接訪問父類的私有屬性,所以通過呼叫父類的構造器類初始化屬性 } public Student(String id, String name, int age) { this(name, age);//因為本類已經有個構造器初始化name和age了,所以交給他來做就行了,也必須寫在第一行 this.id = id; }}