Java Reference
In-Depth Information
Display 5.19
A Person Class (part 5 of 5)
168 private static boolean consistent(Date birthDate, Date deathDate)
169 {
170 if (birthDate == null )
171 return false ;
172 else if (deathDate == null )
173 return true ;
174 else
175 return (birthDate.precedes(deathDate)
176 || birthDate.equals(deathDate));
177 }
178 }
Class Invariant
A statement that is always true for every object of the class is called a class invariant .
A class invariant can help to define a class in a consistent and organized way.
PITFALL: null Can Be an Argument to a Method
If a method has a parameter of a class type, then null can be used as the corresponding
argument when the method is invoked. Sometimes using null as an argument can be
the result of an error, but it can sometimes be an intentional argument. For example,
the class Person ( Display 5.19 ) uses null for a date of death to indicate that the person
is still alive. So null is sometimes a perfectly normal argument for methods such as
consistent . Method definitions should account for null as a possible argument and
not assume the method always receives a true object to plug in for a class parameter.
Notice the defi nition of the method equals for the class Person . A test for equality
has the form
object1.equals(object2)
The calling object object1 must be a true object of the class Person ; a calling object
cannot be null . However, the argument object2 can be either a true object or null .
If the argument is null , then equals should return false , because a true object cannot
reasonably be considered to be equal to null . In fact, the Java documentation specifies
that when the argument to an equals method is null , the equals method should return
false . Notice that our definition does return false when the argument is null .
 
 
Search WWH ::




Custom Search