Java inheritance and hidden public fields

2019-09-29 07:02发布

To simulate some auto-generated classes which looks like this, I made a small jUnit test class to simulate inheritance and hidden fields.

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;
    }
}

My question is: is there any short way to assign the super class value field in a similar way like this:

child.super.value = "test";

instead than creating a specific setter in the ChildClass:

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

I am using Java 7, and I am wondering if it would be possible without modifying the ChildClass nor the ParentClass (Like it could be auto-generated code).

UPDATE: I know you there are several ways to manage this by a) Casting according to Jon's answers: ((ParentClass) child).value = "test"; but not very well b) Instanciate the super class like this (as much as possible): ParentClass myInstance = new ChildClass(); The code myInstance.value will refer to the field in ParentClass

But I wanted to be more focused on the new features of Java 8. For example is it possible to resolve this with a lambda, or another new feature of Java 8?

1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-09-29 07:56

Well you can just cast child to make the compiler resolve the field value with respect to ParentClass instead of ChildClass:

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

But frankly I would a) avoid non-private fields; b) avoid knowingly giving superclasses and subclasses fields with the same name.

Contrary to your comment, the subclass field doesn't "override" the superclass field - it hides it.

查看更多
登录 后发表回答