Jac*_*ack 5 java inheritance overriding this
我在网上搜索了类似的问题,但找不到它.所以,发布在这里.
在以下程序中,为什么'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
}
}
Run Code Online (Sandbox Code Playgroud)
而且以下的输出正如我预期的那样.当我从Parent类调用" 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);
}
}
Run Code Online (Sandbox Code Playgroud)
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
}
}
Run Code Online (Sandbox Code Playgroud)