java中this關鍵字詳解
阿新 • • 發佈:2020-12-05
1)使用this區分同名變數
this.屬性名稱
指的是訪問類中的成員變數,用來區分成員變數和區域性變數(重名問題)
class Person{ private String name; private int age; private String gender; Person(String name,int age,String gender){ this.name = name; this.age = age; this.gender = gender; } }
(2)作為引數傳遞
public class Demo{ public int x = 10; public int y = 15; public void sum(){ // 通過 this 點取成員變數 int z = this.x + this.y; System.out.println("x + y = " + z); }
(3)作為方法名來初始化物件
public class Demo{ public static void main(String[] args){ B b= new B(new A()); } } class A{ public A(){ new B(this).print(); // 匿名物件 } public void print(){ System.out.println("Hello from A!"); } } class B{ A a; public B(A a){ this.a = a; } public void print() { a.print(); System.out.println("Hello from B!"); } }
執行結果:
Hello from A!
Hello from B!