Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
909 views
in Technique[技术] by (71.8m points)

oop - Java inheritance and hidden public fields

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...