I know that an inner class has access to everything in the outer class (because it's a member of that class) but what about the other way around?
Does the outer class have access to private variables and methods within an inner class?
I've seen articles mentioning that inner classes should be private so that they are accessible only to the outer class. What does that do to the accessibility of that inner class?
What is best practices in dealing with access levels when it comes to your inner classes? I'm assuming more encapsulation the better but does that come at the expense of accessibility?
Modifiers. 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.
As the inner class exists inside the outer class we must instantiate the outer class in order to instantiate the inner class. Hence, to access the inner class, first create an object of the outer class after that create an object of the inner class.
They are accessed using the enclosing class name. To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: OuterClass.
Rules of Local Inner Class:The scope of the local inner class is restricted to the block they are defined in. A local inner class cannot be instantiated from outside the block where it is created in. Till JDK 7, the Local inner class can access only the final local variable of the enclosing block.
This topic is covered in some detail by Effective Java (2nd edition) Item 22: "Favor static member classes over nonstatic".
A brief summary:
static
by default. To get technical, Effective Java calls these static member classes, as opposed to inner classes, and uses the term nested class to encompass both the static and nonstatic versions.private
. In this way, an inner class can expose itself only to its outer class.Personally, I'm inclined to implement an inner class whenever doing so allows the inner class's constructors to be private
, i.e. when a class can only be instantiated from one other (outer) class. Any additional encapsulation, such as making the entire inner class private
, is desirable; but public
inner classes are perfectly acceptable. There are many examples in Java, such as AbstractMap.SimpleEntry
.
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