Java 继承 - this 关键字

标签 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
    }
}

此外,以下输出符合我的预期。当我从父类调用“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/

相关文章:

java - Hibernate:在有序列表中删除后插入

c++ - 抽象类继承另一个具有相同函数名的抽象类

python - 如何通过继承扩展django抽象基础模型?

java - 在 eclipse 中进行 Android 开发时,我收到 "must override or implement a supertype method"错误,研究的解决方案不起作用

java - Spring Data JPA 保存列表实体返回列表的顺序相同吗?

C# - 具有继承的显式接口(interface)?

ruby-on-rails - 如何重写类范围内声明的方法?

java - Hashcode 相等是否意味着引用基于引用的相等?

c++ - 需要覆盖逆变变通方法

java - iOS 消费的 Web 服务(在 Amazon 上)安全