Java继承和隐藏的公共字段

рüф*_*ффп -4 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

child.super.value = "test";
Run Code Online (Sandbox Code Playgroud)

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

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

我正在使用Java 7,我想知道如果没有修改ChildClass也不可能ParentClass(就像它可能是自动生成的代码).

更新:我知道有几种方法可以通过以下方式来管理:a)根据Jon的答案进行转换:((ParentClass) child).value = "test";但不是很好b)像这样(尽可能多)实现超类:ParentClass myInstance = new ChildClass(); 代码myInstance.value将引用ParentClass中的字段

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

Jon*_*eet 7

那么你可以只投child使编译器解决该领域value相对于ParentClass代替ChildClass:

((ParentClass) child).value = "test";
Run Code Online (Sandbox Code Playgroud)

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

与您的注释相反,子类字段不会"覆盖"超类字段 - 它隐藏它.