关于 Java 中的this 关键字:
this
翻译为:这个this
是一个引用,是一个变量,this
变量中保存了内存地址指向自身,this
存储在 JVM 堆内存java
对象内部- 创建 100 个
java
对象,每个对象都有this
,也就说有100个不同的this
this
可以出现在【实例方法】里面,this
指向当前正在执行这个动作的对象(this
代表当前对象)this
在多数情况下可以省略不写this
不能使用在带有static
关键字的方法当中this()
只可以出现在构造方法的第一行,前面不可以写任何代码
实例方法就是指不带 static 关键字的方法,实例变量就是指不带 static 关键字的变量。都需要创建对象,然后引用. 的方式去访问
this 就是自身,谁用就是谁
创建 100 个 java
对象,每个对象都有 this
,也就说有100个不同的this
public class Test{
public static void main(String[] args){
Customer c1 = new Customer();
Customer c2 = new Customer();
}
}
class Customer{
String name;
//无参构造器
public Customer(){}
}
以上代码内存图如下:
this
是一个引用,是一个变量,this
变量中保存了内存地址指向自身,this
存储在 JVM 堆内存java
对象内部
this
可以出现在【实例方法】里面,this
指向当前正在执行这个动作的对象(this
代表当前对象)
创建一个实例方法,顾客购物方法,每个顾客购物的动作都不一样,购物这个动作必须顾客这个对象参与。所以需要不同对象去调用,所以需要是实例方法
想要输出是哪一个对象在购物,即 引用.name + 在购物
,此时就用到this
关键字
当不同的对象调用this
关键字所在的方法时,这个this
关键字就代表这个具体的对象
但是在此处的 this
可以省略,因为其中的name
变量是一个实例变量,需要有对象的引用才可以使用
public class Test{
public static void main(String[] args){
Customer c1 = new Customer();
Customer c2 = new Customer();
c1.shopping();
c2.shopping();
}
}
class Customer{
String name;
public Customer(){}
public void shopping(){
System.out.println(this.name + "在购物");
}
}
静态方法不可用 this
注意:以下写法是错误的
以下代码含义是访问当前对象的name
变量。
因为name
是实例变量,需要对象的引用才可以访问,但是doSome
方法是静态方法,访问方式是类名.方法名
,没有对象的参与,不需要创建对象,自然也没有this
的存在
所以在静态方法中不可以使用this
关键字
public static void doSome(){
System.out.println(name);
//相当于
System.out.println(this.name);
}
静态方法怎么访问实例变量?
以下会报错。
因为System.out.println(age);
相当于是System.out.println(this.age);
,意思是访问当前对象的age
变量,可是main
方法是静态方法,不需要对象调用,也就不存在当前对象
要访问实例变量age
,就必须要有对象调用
public class Test{
int age;
public static void main(String[] args){
System.out.println(age);
}
}
正确写法如下:
在这种写法下,变量age
就直接是引用tt
的实例变量,就不存在this
了。
public class Test{
int age;
public static void main(String[] args){
Tset tt = new Test();
System.out.println(tt.age);
}
}
有参构造器中的 this
this
最常见的用法,就是构造方法中区分局部变量和实例变量
等号后面的是形参中的age
,是局部变量
this
指代的是实例变量age
此时的this
关键字不可以省略
public class User{
private int age;
public User(age){
this.age = age
}
}
在无参构造器中调其他构造方法用 this
this
用在实例方法中,代表当前对象。this.
this
用在构造方法中,通过当前构造方法调用其他的构造方法,this(实参);
- 注意:
this()
的用法只可以出现在构造方法中
需求:当调用无参构造器的时候,默认创建的日期是 1970-1-1
public class Date{
private int year;
private int month;
private int day;
public Date(year,month,day){
this.year = year;
this.month = month;
this.day = day;
}
//需求:当调用无参构造器的时候,默认创建的日期是 1970-1-1
public Date(){
this.year = 1970;
this.month = 1;
this.day = 1;
}
}
以上方法比较繁琐,相当于又写了一个有参构造器的代码
用this()
来调用有参构造器即可
public class Date{
private int year;
private int month;
private int day;
public Date(year,month,day){
this.year = year;
this.month = month;
this.day = day;
}
//自动匹配有参构造器
//以下不会创建新对象,同时又可以调用其他构造方法
public Date(){
this(1970,1,1);
}
}