在下面的代码片段中,结果确实令人困惑。
public class TestInheritance {
public static void main(String[] args) {
new Son();
/*
Father father = new Son();
System.out.println(father); //[1]I know the result is "I'm Son" here
*/
}
}
class Father {
public String x = "Father";
@Override
public String toString() {
return "I'm Father";
}
public Father() {
System.out.println(this);//[2]It is called in Father constructor
System.out.println(this.x);
}
}
class Son extends Father {
public String x = "Son";
@Override
public String toString() {
return "I'm Son";
}
}
结果是
I'm Son
Father
为什么“this”在Father构造函数中指向Son,而“this.x”在Father中指向“x”字段。 “this”关键字是如何工作的?
我知道多态的概念,但是[1]和[2]之间不会有区别吗?当 new Son() 被触发时,内存中发生了什么?
最佳答案
默认情况下,Java 中的所有成员函数都是多态的。这意味着当您调用 this.toString() 时,Java 使用动态绑定(bind)来解析调用,调用子版本。当您访问成员 x 时,您访问的是当前作用域的成员(父亲),因为成员不是多态的。
关于java - Java继承中的 "this"关键字是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23055354/