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.
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.
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.
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With