8.6 this关键字

this是类里面经常会出现的,到底什么是this呢。 this就是指当前的对象。
我们用代码来解释这句话:
public class Mobile{
    String name;
    String mon;
    public void setName(String name){
        this.name=name;
    }
    public static void main(String[]args){
        Mobile m=new Mobile();
        m.setName("iphone x");
        System.out.println(m.name));
    }
}
在方法setName里面有这样一行this.name=name,this.name就是当前对象的name,第二个name是参数,那什么是当前对象呢,看main函数的测试代码,
m.setName("iphone x");
这个m就是当前对象。哪个对象调用setName,哪个对象就是this。
this只能出现在非静态方法里面,因为它本身就是一个对象,指当前对象,而静态方法里面是没有对象的。 this用在方法里面,它可以访问所有的属性和方法,例如:
public class Mobile{
    String name;
    String mon;
    public void setName(String name){
        if( ! name.equals(this.getName()))
            this.name=name;
    }
    public String getName(){
        return this.name;
    }
    public static void main(String[]args){
        Mobile m=new Mobile();
        m.setName("iphone x");
        System.out.println(m.getName());
    }
}
setName方法用this调用了getName,一般初学者遇到this都有一个困惑,到底this有什么用,就算删除掉this好像也没什么区别,实际上,不用this,在大部分的情况下,都不会有任何影响。
用了this,就能更明确指代哪些是对象的属性和方法。
上面的代码this.name=name如果删掉this,就无法区分类的属性name还是参数name,这里是要明确吧参数的name赋值给属性name,所以不能省略,否则会被解释成参数name赋值给自己。