Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

java - Access to superclass private fields using the super keyword in a subclass

For a coding project I have a class containing a nested class. The nested class is subclassed within the same outer class. The intention is for the outer class to contain some instances of the nested class which it can hand to other instances of the outer class.

The nested subclass allows the outer class to modify the contents while its superclass allowes the contents to be read and some methods invoked. The superclass objects are thus handed to other objects to links the outer class objects in a chain.

The question I have concerns the access modifiers. Here is a minimalist 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 documentation I was confused by the ability to access the private field of the superclass not being mentioned anywhere. Is there any resource explaining why the subclass is allowed to modify the private field of the superclass in this way?

I am completely fine with this working. I also noticed that it seems to work with data being marked as protected instead of private and not using the super keyword. I am mostly interested in any documentation mentioning this ability of the super keyword. Thanks in advance.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

According to the Java Language Specification

Example 6.6-5. Access to private Fields, Methods, and Constructors

A private class member or constructor is accessible only within the body of the top level class (§7.6) that encloses the declaration of the member or constructor. It is not inherited by subclasses.

So what happens is the inner class can see a non-private field directly since it inherits it.

However, for private fields the inner class has to use super.field to access it since it is not inherited (otherwise you get a compiler error "field is not visible"). Even though it is not inherited it is still accessible because the inner class is inside the outer class and private fields are accessible to anything inside the body of the top level class.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...