java中this关键字详解
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!

浙公网安备 33010602011771号