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