What is the reason of declaring a member of a private inner class public in Java if it still can't be accessed outside of containing class? Or can it?
public class DataStructure { // ... private class InnerEvenIterator { // ... public boolean hasNext() { // Why public? // ... } } }
Unlike a class, an inner class can be private and once you declare an inner class private, it cannot be accessed from an object outside the class. Following is the program to create an inner class and access it. In the given example, we make the inner class private and access the class through a method.
Java inner class can be declared private, public, protected, or with default access whereas an outer class can have only public or default access.
We use inner classes to logically group classes and interfaces in one place to be more readable and maintainable. Additionally, it can access all the members of the outer class, including private data members and methods.
The main advantages of a nested (inner) class are: It shows a special type of relationship, in other words, it has the ability to access all the data members (data members and methods) of the main class including private. They provide easier code because it logically groups classes in only one place.
If the InnerEvenIterator
class does not extend any class or implement any interface, I think it is nonsense because no other class can access any instance of it.
However, if it extends or implements any other non private class or interface, it makes sense. An example:
interface EvenIterator { public boolean hasNext(); } public class DataStructure { // ... private class InnerEvenIterator implements EvenIterator{ // ... public boolean hasNext() { // Why public? // ... } } InnerEvenIterator iterator; public EvenIterator getIterator(){ return iterator; } }
This method can be made public
in order to indicate that it's semantically public, despite the fact that compiler doesn't enforce visibility rules in this particular case.
Imagine that during some refactoring you need to make this inner class top-level. If this method is private
, how would you decide whether it should be made public
, or some more restrictive modifier should be used? Declaring method as public
tells reader the intentions of original author - this method shouldn't be considered an implementation detail.
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