感觉this挺简单的,就是要多看几遍、顾名思义就有感觉了。
this 引用
关键字 this 引用对象自身。
它也可以在构造方法内部,调用同一个类的其他构造方法。
下面代码使用 this 来显式地
引用HighQualityMale
的实例对象的实例变量: girlfriend
以及调用它的getGirlfriend()
方法。
this引用通常
是省略掉的,
public class HighQualityMale{
private HighQualityFemale girlfriend;
public selfIntroduce(){
System.out.println("就是,嗯。。,这是一个关于人类高质量男性的类");
}
public getGirlfriend(HighQualityFemale gf){
System.out.println("我叟先自我介绍一下,以方便宁,加深宁对我的聊解。");
this.seflIntroduce();
return this.girlfriend ;
}
}
上下两个代码段是等价的
public class HighQualityMale{
private HighQualityFemale girlfriend;
public selfIntroduce(){
System.out.println("就是,嗯。。,这是一个关于人类高质量男性的类");
}
public getGirlfriend(HighQualityFemale gf){
System.out.println("我叟先自我介绍一下,以方便宁,加深宁对我的聊解。");
seflIntroduce();
return girlfriend ;
}
}
然而,在引用隐藏数据域以及调用一个重载的构造
方法的时候,this 引用是必须的
。
谈到,必须的
, 好奇心就上来了,要是我就不用呢 ?那你自己试试
使用this引用隐藏数据域
在数据域的 set 方法中,常将数据域名用作参数名。
换种说法,this可以用来区分成员变量和局部变量(重名问题)
隐藏的实例变量,需要 this 引用
隐藏的静态变量可以简单地通过 “类名 .静态变量” 的方式引用。
public class F {
private 1nt i = 5;
private static double k = 0; i
public void setl(int i) { //数据域名用作参数名。
this.i=i; // 隐藏的实例变量就需要使用关键字 this 来引用
}
public static void setKCdouble k) {
F.k = k; //静态变量可以简单地通过 “类名 .静态变量” 的方式引用。
}
}
使用this调用构造方法
关键字 this 可以用于调用同一个类的另一个构造方法
this(1.0)
这一行调用带 double 值参数的第一个构造方法。
注意:
- Java 要求在构造方法中,语句 this( 参数列表)应在任何其他可执行语句之前出现。
- this() 不能使用在普通方法中 只能写在构造方法中
比如这给就错了:
public class C {
private int p;
public C(){
System.out.println("C* s no-arg constructor invoked");
this(0);
}
}
一个小测试例子:
public class TestThis {
private int n = 1;
TestThis(int n){
this.n = n;
}
TestThis(){
this(10);
}
public void printThis(){
System.out.println(this);
}
public static void main(String[] args) {
TestThis tt = new TestThis();
TestThis t2 = new TestThis(5);
System.out.println(t2.n);
tt.printThis();
t2.printThis();
}
}
控制台输出:
5
TestThis@1b6d3586
TestThis@4554617c
Process finished with exit code 0
end