this通常指當前對象,它有兩個用處: 1.利用this引用當前對象的某個方法或某個成員; 2.調用當前對象的其他構造方法
如果想引用父類的某種東西或調用父類的某個構造方法用super
this和super調用構造方法時,根據其后所帶的參數來確定調用的具體是哪個構造方法,如super()表示調用的是父類的無參的構造方法
另外,在靜態方法中不能用this,因為靜態方法不屬于任何特定的對象,它只屬于當前類,而this是屬于當前類的對象的
public class Teacher extends Person { PRivate String name = "tom"; public Teacher() { super(2); System.out.println("this is a teacher"); } public static void main(String[] args) { Teacher teacher = new Teacher(); System.out.println(teacher.name); }}class Person { public Person() { System.out.println("this is a Person"); } public Person(int i) { System.out.println("Person"); }}輸出結果為
在子類Teacher的構造方法中調用的是父類帶參數的構造方法,而且super()必須寫在子類構造方法的第一行,否則編譯報錯;在main方法中如果使用this.name,編譯時會報錯。
|
新聞熱點
疑難解答