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

来源:互联网 发布:补水保湿 知乎 编辑:程序博客网 时间:2024/05/02 01:22

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


0 0
原创粉丝点击