I
I
iscateli2021-12-26 14:50:24
Java
iscateli, 2021-12-26 14:50:24

What's the design?

I met a construction of the form

public static final Person NULL = new NullPerson();

what does it mean and how to read?

text from Bruce Eckel's "Java Philosophy" (p. 488):

A simple example: Many systems have a Person class that represents a person. If information about a person is not available (or not enough) in the code, traditionally the programmer would use null as the value of the reference. You can also create a null object instead. But even though a null object responds to all the messages that a "real" object responds to, there must be some way to test for null objectness. The easiest way is to use the identification interface:

//: net/mindview/util/Null.java 
package net.mindview.util; 
public interface Null {}

This solution allows you to use instanceof to detect null objects
and, more importantly, does not require the isNull method to be included in all classes (which
will essentially model RTTI - why not use the built-in tools?).


//: typeinfo/Person.java 
// Класс с null-объектом, 
import net.mindview.util.*;
class Person {
  public final String first; 
  public final String last; 
  public final String address;
  // И т.д.
  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();
} 
//'.~

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Vodakov, 2021-12-26
@iscateli

public static final Person NULL = new NullPerson();

Declaring a public static NULL field, of type Person initialized with an object of type NullPerson.
The NullPerson object, apparently, is a child object of the Person class that implements the Null interface
. This is what is said in the text.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question