All classes extend java.lang.Object
but you never state it.
So all classes inherit some methods we mentioned earlier (and several others, coming later), which can be overridden:
public Object clone (); // For copying objects
public boolean equals (Object b); // For equating objects, not just references
public String toString (); // For making a string representation of an object
Your classes should always override toString ()
because it is extremely useful, particularly for debugging. You can then say, for example, System.out.println (myObject);
and your overridden toString ()
will be called automatically.
Arrays are also really Objects, so they implement these methods and are always cloneable.
Notice that because clone ()
is inherited from Object
its return type can only be Object
and so we need to cast a cloned object to its real type:
Person p2 = (Person) p1.clone ();
Similarly, the input parameter for equals ()
can only be Object
so we have to work out the real type within our overriding code. We will show how to do that in due course.
NB: Since Java 5 overriding clone ()
with the correct return type is legal. The compiler sorts it out and generates the same byte code as before (casting Object
to the required type).