Reputation: 13442
I read the following code on NULL object pattern but there is one thing that I am really not clear on. The code follows.
//Null.java
package test_package1;
public interface Null {
}
//Person.java
class Person {
public final String first;
public final String last;
public final String address;
// etc.
public Person(String first, String last, String address){
this.first = first;
this.last = last;
this.address = address;
}
public String toString() {
return "Person: " + first + " " + last + " " + address;
}
public static class NullPerson
extends Person implements Null {
private NullPerson() { super("None", "None", "None"); }
public String toString() { return "NullPerson"; }
}
public static final Person NULL = new NullPerson();
}
Now, I've a question: why should the following code snippet work:
public static final Person NULL = new NullPerson();
The NullPerson class has a private constructor, so how is the object instantiation possible outside the class scope?
Secondly, what is the need of making the NullPerson class as a static inner class?
Upvotes: 0
Views: 139
Reputation: 280181
An enclosing type has access to any member (and that member's members) declared (nested) within it, regardless of its declared access modifiers.
Secondly, what is the need of making the NullPerson class as a static inner class?
To make what they did possible. In my opinion, the type itself should be private
. No other types can do anything with NullPerson
.
Upvotes: 3