Having a static "NULL" object in Java?

While looking at the code for the library that I am using, I came across this piece of code:

public class SomeClass { private static final class Null { /* ... */ } public static final Object NULL = new Null(); } 

Is it common practice to have a special NULL object for a class that is used instead of Java null ? What are the benefits of this, instead of using Java built in to null ?

The main reason I'm curious is that, while using the library, I continued to check if SomeClass was empty, not realizing that they were using a special NULL object to denote the null SomeClass object.

EDIT: For those who are wondering, the exact source code 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(); } 
+7
source share
5 answers

A null object template can sometimes be useful - so you do not use a null reference, but have an actual object with neutral behavior. However, the implementation you gave there does not make sense:

  • Null does not apply to SomeClass, what I expect from it
  • Null declared as Object , not SomeClass .

Be that as it may, I would say that the code is useless. But with the right implementation, the template may be useful.

+10
source

This is a "null object pattern". The advantage is that you do not need to explicitly check for null, avoiding NPE.

+2
source

A better name for their class would be Empty or the like. Using the java keyword variant is not a good idea - it leads to confusion ... and to such questions.

In addition, an usually empty object is a special instance of the class:

 public class SomeClass { public static final SomeClass EMPTY = new SomeClass("parameters that make it empty"); } 
+1
source

It depends on the use. There may be NULL classes, which, for example, are a Null data type that is NOT equal to zero in java. Example: http://www.snmp4j.org/doc/org/snmp4j/smi/Null.html

Otherwise, it would not be idiomatic java to wrap a null value in a NULL object.

+1
source

Sample of a null object .

I used it once in my projects and I won’t do it anymore, because it’s difficult when it comes to serialization

+1
source

All Articles