While browsing through some code for a library I'm using, I came across this code snippet:
public class SomeClass {
private static final class Null {
/* ... */
}
public static final Object NULL = new Null();
}
Is this a common practice to have a special NULL object for a class that gets used instead of Java's null
? What are the upsides to doing this instead of using Java's built in null
?
The main reason I'm curious is that while using the library, I kept checking whether SomeClass was null, without realizing that they were using a special NULL object to denote a null object of SomeClass.
EDIT: For those wondering, the exact code from the source is:
public class JSONObject {
private static final class Null {
protected final Object clone() {
return this;
}
public boolean equals(Object object) {
return object == null || object == this;
}
public String toString() {
return "null";
}
}
public static final Object NULL = new Null();
}