简体   繁体   中英

Is there any sense in access modifiers for fields of the private inner class?

Suppose I have an outer class with an inner class inside. The inner class has four fields with all possible access modifiers.

class Outer {
    private class Inner {
        public int publicField;
        protected int protectedField;
        int packagePrivatefield;
        private int privateField;
    }

    void doSomethingWithFields() {
        Inner inner = new Inner();
        inner.publicField = 111;
        inner.protectedField = 111;
        inner.packagePrivatefield = 111;
        inner.privateField = 111;
    }
}

The inner class is private, so I can't create instances of it outside the Outer class. Inside the Outer class, if I create an instance of the inner class and try to change the value for each of the fields I will succeed to do that. So I see that there is no sense in access modifiers for the above fields. Is there?

Edited: The main question is: Which access modifiers should I choose for members of the private inner class? Inner class can not only implement interface. I can put some difficult structure with logic into it.

Access modifiers have a say in inheritance. Another inner private class that extends that class you talk of does not have the privileges of the outer class.

public class Main {
    private class Test {
        protected int hello;
    }
    private class TestNext extends Test {
        private TestNext() {
            this.hello = 1;
        }
    }
}

Will compile, but if hello was private, it would not.

Right, if the inner class is private it doesn't make sense.

But keep in mind that inner classes are not very beautiful in general, you should rather group multiple classes with packages.

Yes. You are correct. But only if you have single nested inner There is no different between having various access modifiers in a private inner class. Nothing can be seen out of the class. But if you have another nested inner class then your access modifiers will matter. eg

class A{
   private class B{
      class C{}
   }
}

in this case class B's field and methods access modifiers will matter

If the inner class does not implement any Interface or inheritance, then there is no point of specifying access modifiers.

If the inner class inherits something, it does make sense in that context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM