1. 程式人生 > 實用技巧 >java中this和super的用法及區別

java中this和super的用法及區別

this

  • 用法1:代表當前物件本身

  • 用法2:方法形參和類成員變數重名,用this進行區別

class demo{
  private int age = 10;
  
  public int getAge(int age){
   this.age = age;
   return this.age;
  }
}
  • 用法3:引用建構函式

這個和 super 放在一起講,見下面。

super

  • 用法1:引用父類成員變數

可用 super.xxx 來引用父類的成員

  • 用法2:子類呼叫父類方法或變數

呼叫變數前需要先引用 父類方法:

class father{
	String name;
	void eat(){
		name = "666";
	}
}
class son extends father{
	super.eat();
	System.Out.println(super.name);
}

不呼叫方法只調用變數的話,變數值為null

this、super引用建構函式

必須寫在建構函式的第一條

無引數時,表示呼叫建構函式

有引數時,表示呼叫具有相同引數的建構函式

super():引用父類無參建構函式

super(引數1,引數2):引用父類相同形參的建構函式

this():引用本類無參構造方法

this(引數1,引數2):引用本類具有相同形參的構造方法