我在网上搜索了类似的问题,但没有找到。所以,在这里发帖。
在下面的程序中,为什么'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没有虚拟字段,所以i
领域在printName
总是指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
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)