什么是
this
引用:
java
编译器给每个
“
成员方法
“
增加了一个隐藏的引用类型参数,该引用参数指向当前对象
(
成员方法运行
时调用该成员方法的对象
)
,在成员方法中所有成员变量的操作,都是通过该引用去访问
。只不过所有的 操作对用户是透明的,即用户不需要来传递,编译器自动完成。
this一共有两个作用:
第一个作用:this就是一个引用,类型就是当前类。
class Person(){ this 类型就是Person}
class Cat(){this 类型就是Cat}
指向当前对象,构造器中this指向的就是当前正在构造的对象。
this.属性 此时一定是属性的全名。
第二个作用:在一个构造方法中调用其他构造方法。
package mjh.week.day5;
public class Test2 {
Test2() {
this(18);
System.out.println("无参");
}
Test2(int a) {
System.out.println("int");
}
Test2(String b) {
System.out.println("string");
}
public static void main(String[] args) {
new Test2();
}
}
this
引用的特性
1. this
的类型:对应类类型引用,即哪个对象调用就是哪个对象的引用类型
2. this
只能在
"
成员方法
"
中使用
3.
在
"
成员方法
"
中,
this
只能引用当前对象,不能再引用其他对象,具有
final
属性
4. this
是
“
成员方法
”
第一个隐藏的参数,编译器会自动传递,在成员方法执行时,编译器会负责将调用成员方法对象的引用传递给该成员方法,this
负责来接收。
package mjh.week.day5;
public class Date {
public int year;
public int month;
public int day;
public void setDate(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public void printDate() {
System.out.println(this.year + "/" + this.month + "/" + this.day);
}
public static void main(String[] args) {
Date d = new Date();
d.setDate(2021, 12, 28);
d.printDate();
}
}