this 关键字用来表示当前对象本身,或当前类的一个实例,通过this可以调用对象的所有方法和属性。
1 public class Demo { 2 private int x = 10; 3 private int y = 15; 4 5 public void sum(){ 6 //通过this获取成员变量,this可以省略。 7 int z = this.x + this.y; 8 System.out.println("x+y = "+z); 9 } 10 11 public static void main(String[] args) { 12 Demo demo = new Demo(); 13 demo.sum(); 14 } 15 }
使用this区分同名变量
1 public class Demo { 2 private String name; 3 private int age; 4 5 public Demo(String name,int age){ 6 //this不能省略,this.name 指的是成员变量, 等于后面的name 是传入参数的变量,this可以很好的区分两个变量名一样的情况。 7 this.name = name; 8 this.age = age; 9 } 10 public static void main(String[] args){ 11 Demo demo = new Demo("微学院",3); 12 System.out.println(demo.name + "的年龄是" + demo.age); 13 } 14 }
使用this作为方法名来实例化对象
1 public class Demo { 2 private String name; 3 private int age; 4 5 public Demo(){ 6 /** 7 * 构造方法中调用另一个构造方法,调用动作必须置于最起始位置。 8 * 不能在构造方法之外调用构造方法。 9 * 一个构造方法只能调用一个构造方法。 10 */ 11 this("微学院",3); 12 } 13 14 public Demo(String name,int age){ 15 this.name = name; 16 this.age = age; 17 } 18 19 public static void main(String[] args){ 20 Demo demo = new Demo(); 21 System.out.println(demo.name + "的年龄是" + demo.age); 22 } 23 }
this作为参数传递
1 class Person{ 2 public void eat(Apple apple){ 3 Apple peeled = apple.getPeeled(); 4 System.out.println("Yummy"); 5 } 6 } 7 class Peeler{ 8 static Apple peel(Apple apple){ 9 return apple; 10 } 11 } 12 class Apple{ 13 Apple getPeeled(){ 14 //传入this,就是传入Apple。 15 return Peeler.peel(this); 16 } 17 } 18 public class This{ 19 public static void main(String args[]){ 20 new Person().eat(new Apple()); 21 } 22 }