標籤:hone gets person scree oat ati mem 建構函式 one
1.this關鍵字代表當前對象
this.屬性 操作當前對象的屬性
this.方法 調用當前對象的方法
2.封裝對象的屬性的時候,經常會使用this關鍵字
public class Telphone { private float screen; private float cpu; private float mem; public void sendMessage(){ System.out.println("sendMessage"); } public float getScreen() { return screen; } public void setScreen(float screen) { this.screen = screen; // 操作當前對象的屬性 this.sendMessage(); // 調用當前對象的方法 } public float getCpu() { return cpu; } public void setCpu(float cpu) { this.cpu = cpu; } public float getMem() { return mem; } public void setMem(float mem) { this.mem = mem; } public Telphone(){ System.out.println("com.imooc.Telphone"); } public Telphone(float newScreen,float newCpu,float newMem){ if(newScreen<3.5f){ System.out.println("..............."); screen = 3.5f; } cpu = newCpu; mem = newMem; System.out.println("----------------"); }}this
this 是自身的一個對象,代表對象本身,可以理解為:指向對象本身的一個指標。
this 的用法在 Java 中大體可以分為3種:
1.普通的直接引用
這種就不用講了,this 相當於是指向當前對象本身。
2.形參與成員名字重名,用 this 來區分:
package s2;class Person { private int age = 22; public Person() { System.out.println("初始化年齡:" + age); } public int getAge(int age) { this.age = age; // 形參與成員名字重名 return this.age; }}public class Test03 { public static void main(String[] args) { Person Harry = new Person(); System.err.println("Harry‘s age is:" + Harry.getAge(33)); }}
運行結果:
初始化年齡:22Harry‘s age is:33
3.引用建構函式
這個和 super 放在一起講,見下面
Java 中的this關鍵字