JAVA OOP——使用 this引用隐藏数据域、使用 this 调用构造方法

本文介绍了JAVA中关键字this的使用,包括如何使用this引用隐藏数据域以解决重名问题,以及如何在构造方法中使用this调用其他构造方法。文章通过一个小测试例子来帮助读者理解this的用法,并强调了构造方法中this调用的规则。


感觉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 = 5private 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 值参数的第一个构造方法。

注意:

  1. Java 要求在构造方法中,语句 this( 参数列表)应在任何其他可执行语句之前出现。
  2. 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

adingable

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值