java - 通过继承隐藏字段

标签 java oop inheritance scjp

在下面的代码示例中:

class Parent { 
    int x =5;
    public Integer aMethod(){

        System.out.print("Parent.aMthod ");
        return x;
    }
}

class Child extends Parent {
    int x =6;
    public Integer aMethod(){
        System.out.print("Child.aMthod "); 
        return x;
    }
}


class ZiggyTest2{

    public static void main(String[] args){

        Parent p = new Child();
        Child c = new Child();

        System.out.println(p.x + " " + c.x);

        System.out.println(p.aMethod() + "  \n");
        System.out.println(c.aMethod() + "  \n");
    }   
}

输出:

5 6
Child.aMthod 6  

Child.aMthod 6

为什么当 p.x 打印 6 时 p.aMethod() 不打印 6?

谢谢

编辑

哎呀,一个小错别字:问题应该是“为什么 p.aMethod() 在 p.x 打印 5 时不打印 5”——谢谢@thinksteep

最佳答案

当您访问像 p.x 这样的类成员字段(实例变量)时,不会进行多态解析。换句话说,您将从编译时已知的类中获得结果,而不是运行时已知的结果。

对于方法调用,这是不同的。它们在运行时被分派(dispatch)到引用指向的实际类的对象,即使引用本身具有父类(super class)型。 (在 VM 中,这是通过 invokevirtual 操作码发生的,参见例如 http://java.sun.com/docs/books/jvms/second_edition/html/Instructions2.doc6.html#invokevirtual)。

关于java - 通过继承隐藏字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8647248/

相关文章:

java - 如何从 MainActivity 添加到 network_security_config

java - 根据加在一起的字母值对字符串进行排序。 ( java )

java - 我可以将 Oracle JDBC 驱动程序 JAR 捆绑在 Docker 镜像中吗?

C++虚拟克隆方法,异常继承

c++ - 类上下文中的错误 LNK2005 和 LNK1169

java - Guava 的 Optional 类有什么意义

language-agnostic - 设计软件时应该考虑性能吗?

javascript oo 问题

java - 线程中的异常 "main"org.hibernate.exception.SQLGrammarException : ORA-00926: missing VALUES keyword

c++ - 从基本类型的 vector 访问派生成员