为什么子类getter返回其超类的属性?

时间:2019-05-19 19:02:35

标签: java inheritance polymorphism

我在考试中有这个确切的问题:

以下程序显示什么,为什么?

class Base {
    private String className = "Base";
    public String name() { return this.className; }
}

class Derived extends Base {
    private String className = "Derived";
}

public class Test {
    public static void main(String[] args) {
        System.out.println(new Derived().name());
    }   
}

所以输出是“ Base”,但是我想确切地知道为什么。吸气剂name()是否应该返回子类属性?

2 个答案:

答案 0 :(得分:1)

正如安迪·特纳(Andy Turner)所说,类字段不是多态的。但是这段代码将达到您的期望:

sess = tf.Session()
with sess.as_default():
    tensor = tf.range(10)
    print_op = tf.print(tensor)
    with tf.control_dependencies([print_op]):
      out = tf.add(tensor, tensor)
    sess.run(out)

答案 1 :(得分:1)

仅在超类中定义私有字段,而子类具有自己的私有字段(即使名称相等)

如果需要解决方案,则应定义受classname保护的

喜欢这个:

class Base {
    protected String getClassName(){
        return "Base";
    }
    public String name() { return this.getClassName(); }
}

class Derived extends Base {

    @Override
    protected String getClassName(){
        return "Derived";
    }

}

public class Test {
    public static void main(String[] args) {
        System.out.println(new Derived().name());
    }   
}
相关问题