Java – use the super keyword in subclasses to access private fields of superclasses

For coding projects, I have a class that contains nested classes Nested classes subclass in the same external class Its purpose is to make the external class contain some instances of the nested class, which can be passed to other instances of the external class

Nested subclasses allow external classes to modify content, while superclasses allow reading content and calling certain methods Therefore, superclass objects are handed over to other objects to link external class objects in the chain

I'm concerned about access modifiers This is a simple code example:

abstract class OuterClass {


    protected class NestedSuperClass<T> {
        private T data;

        public NestedSuperClass (T t) {
            this.data = t;
        }

        public T getOutput() {
            return data;
        }
    }

    protected class NestedSubClass<T> extends NestedSuperClass<T> {
        public NestedSubClass (T t) {
            super(t);
        }

        protected void setOutput(T t) {
            super.data = t;
        }
    }
}

When looking up some documents, I was confused by the ability to access the private fields of the superclass and was not mentioned anywhere Are there resources to explain why subclasses are allowed to modify private fields of superclasses in this way?

I can work like this I also noticed that it seems possible to use data marked as protected rather than private instead of super keywords What I am most interested in is any document that provides this ability of super keywords Thank you in advance

Solution

According to Java language specification

What happens is that the inner class can directly see the non - private field because it inherits it

However, for private fields, the inner class must use super Field to access it because it is not inherited (otherwise you get the compiler error "field is invisible") Even if it is not inherited, it is still accessible because the inner class is in the outer class, and the private field can be accessed by anything in the body of the top-level class

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>