Java-this

  • 当方法中的参数和类中变量重名时,使用  this.变量 调用成员变量。
public class test1 {
   String name;
   int age;
   public void te(String name, int age) {
       this.name = name;
       System.out.println(age);
   }
   public static void main(String[] args) {
       test1 a = new test1();
        a.te("heel", 50);
       System.out.println(a.name);
       System.out.println(a.age);
    }
}

此处this指当前对象,运行结果:

  • 使用this调用本类中的其他方法,格式:this.方法名(参数)
public class test1 {
    public void first() {
        System.out.println("first");
    }
    public void second() {
        this.first();  //second方法调用first方法
        System.out.println("second");
    }
}
  • this调用本类中的构造方法,格式:this(参数)
public class test1 {
   public test1(String name){
   }
   public test1(String a,int b) {
       this(a);  //根据参数个数来调用本类中的构造方法
   }
}
  • 使用return this返回当前实例化对象

 

猜你喜欢

转载自www.cnblogs.com/ddpapa/p/10717662.html