Java this 关键字返回当前类实例变量

The this keyword can be used to return current class instance.

We can return the this keyword as an statement from the method. In such case, return type of the method must be the class type (non-primitive). Let’s see the example:

package com.hotmail.henrytien;

public class ThisReturn {
public ThisReturn getThisReturn() {
    return this;
}
void msg() {
    System.out.println(" Hello Java");
}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    new ThisReturn().getThisReturn().msg();
}

}

Let’s prove that this keyword refers to the current class instance variable. In this program, we are printing the reference variable and this, output of both variables are same.

package com.hotmail.henrytien;

public class A5 {
A5(){
    System.out.println(this); //prints same reference ID 
}
public static void main(String[] args) {
    A5 obj = new A5();
    System.out.println(obj); //prints the reference ID  
}
}

output:
com.hotmail.henrytien.A5@5d748654
com.hotmail.henrytien.A5@5d748654


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值