1. this是什么
- this是一个变量,this是一个引用,它存储了当前对象的内存地址,指向自身,this代表了当前对象
2.通过一个例子来说明
@author 帅的天理难容
public class Customer {
//定义一个实例变量
String name;
public Customer() {
}
public Customer(String name) {
this.name = name;
}
public void shopping(){
System.out.println(name+"在购物");
}
}`
public class Test {
public static void main(String[] args) {
Customer c1 = new Customer("张三");
c1.shopping();
}
}
运行结果
- Customer类中的name是一个实例变量,要想访问name需要先创建对象,那么shopping方法中的name为什么可以访问?
- 我们创建了对象c1,c1调用了shopping方法,那么shopping方法中的name应该是c1.name,但显然不能在Customr类的shopping方法中写死c1.name,我们应该怎么做?
- 开始我们说过,name是当前对象的内存地址,那么我们可以将shopping方法中的name写为this.name代表当前对象的name属性。
- 为什么在开始并没有写this关键字,代码没有报错,成功运行
- 因为this关键字在某些情况下可以省略
3.this关键字什么时候可以省略
- Customer类中的有参构造方法中也有this关键字,我们可以省去这个this,运行发现是null,为什么?
- 因为Java当中有就近原则,当省去了this关键字,这俩个name就与就与实例变量无关
- 大部分情况下this关键字可以省略
4.this关键字不能使用在静态方法中
- 静态方法的调用不需要对象,当然不需要this关键字
5.this()方法
- this()方法是通过当前构造方法调用一个本类的其它构造方法
- 语法格式this(实际参数列表)
- 例如本类中的无参构造方法
public Customer() {
this("王五");
}
- 调用无参构造创建对象,调用shopping方法,会出现(王五在购物)的运行结果
- 注意,this()必须是构造器中的第一行代码