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
本文介绍了Java中this关键字的应用,包括使用this返回当前类实例的方法及如何通过this引用当前类的实例变量。通过示例代码展示了this关键字的具体使用场景。
6万+

被折叠的 条评论
为什么被折叠?



