Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.

like image 388
Dumas45 Avatar asked Aug 08 '14 13:08

Dumas45


People also ask

Can we use private access modifier for class?

At the member level, you can also use the public modifier or no modifier (package-private) just as with top-level classes, and with the same meaning. For members, there are two additional access modifiers: private and protected . The private modifier specifies that the member can only be accessed in its own class.

Which of the following access modifier can be accessed with inner class?

Like any other instance variable, we can have access modifier private, protected, public, and default modifier. Like class, an interface can also be nested and can have access specifiers.

Can a private variable be accessed from a inner class?

An inner class is a friend of the class it is defined within. So, yes; an object of type Outer::Inner can access the member variable var of an object of type Outer .

What modifiers may be used with an inner class?

You can use the same modifiers for inner classes that you use for other members of the outer class. For example, you can use the access specifiers private , public , and protected to restrict access to inner classes, just as you use them to restrict access do to other class members.


1 Answers

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.

like image 89
Xabster Avatar answered Oct 06 '22 22:10

Xabster