java this关键字

在构造方法中实用this

People.java

public class People{
    int leg,hand;
    String name;
    People(String s){
        name=s;
        this.init();   //可以省略this,即将this.init();写成init();
    }
    void init(){
       leg=2;
       hand=2;
       System.out.println(name+"有"+hand+"只手"+leg+"条腿");
    }
    public static void main(String args[]){
      People boshi=new People("布什"); //创建boshi时,构造方法中的this就是对象boshi
    }
} 

在实例方法中使用this

class A{
         int x;
         static int y;
         void f(){
              this.x=100;
              A.y=200;
         }

}

   上述A类的实例方法f中出现了this,this就代表使用f的当前对象。所以,“this.x”就表示当前对象的变量x,当对象调用方法f时,将100赋给该对象的变量x,因此,当一个对像调用方法时,方法中的实例成员变量就是值分配给该对象的实例成员变量。而static变量和其他对象共享。上述也可以写成

class A{
         int x;
         static int y;
         void f(){
              int x;
              this.x=100;
              y=200;
         }

}

   但是,当实例成员变量的名字和局部变量的名字相同时,成员变量前面的类名"this"或"类名."就不可以省掉。

原文地址:https://www.cnblogs.com/yihujiu/p/5990430.html