[英]Variable binding and keyword this in Java
在下面的代码中,方法getX()中的变量x如何绑定到类A实例的成员字段,即使在运行时'this'指的是类型B的对象。这是在编译时还是在运行时发生的时间。
class A {
public void getX(){
Class cls = this.getClass();
System.out.println("The type of the object is: " + cls.getName());
System.out.format("value of x = %d\n", this.x);}
public int x = 0;
}
public class B extends A {
public static void main(String[] args) {
B obj = new B();
obj.getX();}
public int x = 1;
}
输出是:
The type of the object is: B
value of x = 0
字段未以多态方式解析。 在编译时,静态解析this.x
以“获取在类A中定义的字段x的值”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.