this

Posted hapyygril

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了this相关的知识,希望对你有一定的参考价值。

普通方法中,this总是指向调用该方法的对象;
构造方法中,this总是指向正要初始化的对象;
static方法不能使用this;

package mypro01;

public class Teacher {
    
    
    String name;
    int id;
    
    //构造方法中,this总是指向正要初始化的对象;
    
    public Teacher(String name) {
        this.name = name;
        System.out.println(this.name+" is a teacher");
    }
    
    public void setName(String name) {
        this.name=name;
    }
    
    //普通方法中,this总是指向调用该方法的对象;
    public void teach() {
        System.out.println(this.name+" is teaching");
    }
    
    public static void main(String[] args) {
        Teacher t = new Teacher("wang");//wang is a teacher
        t.setName("qiao");
        t.teach();  //qiao is teaching
    }  
      
  }

 

以上是关于this的主要内容,如果未能解决你的问题,请参考以下文章