1. 程式人生 > >Java——this和static關鍵字

Java——this和static關鍵字

this關鍵字

編譯器優化:就近原則,取最近的同變數名

1 this表示呼叫本類屬性
只要在類中訪問類的屬性,一定要加上this關鍵字

2 this表示呼叫本類方法
a.呼叫普通方法: this.方法名(引數)
當有類的繼承關係時,呼叫本類方法時一定要加this關鍵字
b.呼叫構造方法: this(引數)

注意:
1> this呼叫構造方法必須放在構造方法首行
2> this呼叫構造方法不允許成環

eg:
public Person(){
System.out.println("*******");
}
public Person(String name){
this();
this.name=name;
}
public Person(String name,int age){
this(name);
this.age=age;
}

3 this表示當前物件

static關鍵字:

1.static變數——類屬性(靜態屬性)
static屬性稱為類屬性,儲存在全域性資料區中(方法區——所有物件共享區域),通過類名呼叫,與物件例項化無關,有預設值。
描述共享屬性使用static屬性(使用頻率少)

2.static方法——類方法(靜態方法)
通過類名呼叫,與物件例項化無關。常見工具類方法

Person.fun();
類似:陣列方法
Arrays.sort(陣列名);
arraycopy();

注意:
1-> 區域性變數不可用static修飾
2-> private,static不可用於外部類,但可用於內部類