Important Methods of java.lang.Object
As
we’ve noted, all
classes extend, directly or indirectly,
java.lang.Object
. This class defines several
important methods that you should consider overriding in every class
you write. Example 3-6 shows a class that overrides
these methods. The sections that follow the example document the
default implementation of each method and explain why you might want
to override it. You may also find it helpful to look up
Object
in the reference section for an API
listing.
Some of the syntax in Example 3-6 may be unfamiliar
to you. The example uses two Java 5.0 features. First, it implements
a parameterized, or generic, version of the
Comparable
interface. Second, the example uses the
@Override
annotation to emphasize (and have the compiler verify) that certain
methods override Object
.
Parameterized types and annotations are covered in Chapter 4.
Example 3-6. A class that overrides important Object methods
// This class represents a circle with immutable position and radius. public class Circle implements Comparable<Circle> { // These fields hold the coordinates of the center and the radius. // They are private for data encapsulation and final for immutability private final int x, y, r; // The basic constructor: initialize the fields to specified values public Circle(int x, int y, int r) { if (r < 0) throw new IllegalArgumentException("negative radius"); this.x = x; this.y = y; this.r = r; } // This is a "copy constructor"--a useful alternative to clone() ...
Get Java in a Nutshell, 5th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.