Java inheritance and hidden public fields

微笑、不失礼 提交于 2019-12-13 09:57:09

问题


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:


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.



来源:https://stackoverflow.com/questions/30057148/java-inheritance-and-hidden-public-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!