我在网上搜索了类似的问题,但没有找到。所以,在这里发帖。
在下面的程序中,为什么'i'的值打印为100?
AFAIK 'this' 指的是当前对象;在这种情况下是“TestChild”并且类名也被正确打印。但是为什么实例变量的值不是200呢?
public class TestParentChild {
public static void main(String[] args) {
new TestChild().printName();
}
}
class TestChild extends TestParent{
public int i = 200;
}
class TestParent{
public int i = 100;
public void printName(){
System.err.println(this.getClass().getName());
System.err.println(this.i); //Shouldn't this print 200
}
}
此外,以下输出符合我的预期。当我从父类调用“this.test()”时,子类方法被调用。
public class TestParentChild {
public static void main(String[] args) {
new TestChild().printName();
}
}
class TestChild extends TestParent{
public int i = 200;
public void test(){
System.err.println("Child Class : "+i);
}
}
class TestParent{
public int i = 100;
public void printName(){
System.err.println(this.getClass().getName());
System.err.println(this.i); //Shouldn't this print 200
this.test();
}
public void test(){
System.err.println("Parent Class : "+i);
}
}
最佳答案
Java 没有虚拟字段,因此 printName
中的 i
字段始终引用 TestParent.i
而不是任何子代。
在 Java 中通过继承实现的多态性只发生在方法中,所以如果你想要你所描述的行为,那么你会想要这样:
class TestChild extends TestParent{
private int i = 200;
@Override
public int getI() { return this.i; }
}
class TestParent{
private int i = 100;
public int getI() { return this.i; }
public void printName(){
System.err.println( this.getClass().getName() );
System.err.println( this.getI() ); // this will print 200
}
}
关于Java 继承 - this 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14097666/