Java继承和隐藏的公共字段

时间:2015-05-05 15:25:48

标签: java oop inheritance shortcut

为了模拟一些自动生成的类,我创建了一个小的jUnit测试类来模拟继承和隐藏字段。

public class ClassDerivationTest {

    @Test
    public void testChild() {

        ChildClass child = new ChildClass();

        // Implicit boolean as it is hiding the super value
        child.value = true;

        // one way to update the parent value
        // child.setParentVal("true");

        // child.super.value = "test";
    }

    public class ChildClass extends ParentClass {
        public boolean value;
    }

    public class ParentClass {
        public String name;
        public String value;
    }
}

我的问题是:是否有任何简短的方法以类似的方式分配超类value字段:

child.super.value = "test";

而不是在ChildClass中创建特定的setter:

    // Imagine this method is not existing for the question
    public void setParentVal(String val) {
        super.value = val;
    }

我正在使用Java 7,我想知道是否可以在不修改ChildClassParentClass的情况下(就像它可能是自动生成的代码一样)。

更新: 我知道你有几种方法可以解决这个问题  a)根据Jon的答案进行施法:((ParentClass) child).value = "test";但不是很好  b)像这样(尽可能)实现超类:ParentClass myInstance = new ChildClass();     代码myInstance.value将引用ParentClass

中的字段

但我想更专注于Java 8的新功能。  例如,是否可以使用lambda或Java 8的另一个新功能解决此问题?

1 个答案:

答案 0 :(得分:7)

嗯,你可以强制child使编译器解析value而不是ParentClass的字段ChildClass

((ParentClass) child).value = "test";

但坦率地说,我会避免非私人领域; b)避免故意给出具有相同名称的超类和子类字段。

与您的评论相反,子类字段不会覆盖"超类字段 - 它隐藏它。

相关问题