Object: The Cosmic Superclass
All classes defined without an explicit extends clause automatically extend Object

Overriding the toString Method
Returns a string representation of the object
Useful for debugging:
Rectangle box = new Rectangle(5, 10, 20, 30);
String s = box.toString();
// Sets s to java.awt.Rectangle[x=5,y=10,width=20,height=30]"
toString is called whenever you concatenate a string with an object:
"box=" + box;
// Result: "box=java.awt.Rectangle[x=5,y=10,width=20,height=30]"
Object.toString prints class name and the hash code of the object
BankAccount momsSavings = new BankAccount(5000);
String s = momsSavings.toString();
// Sets s to something like "BankAccount@d24606bf"
To provide a nicer representation of an object, override toString:
public String toString()
{
return "BankAccount[balance=" + balance + "]";
}
This works better:
BankAccount momsSavings = new BankAccount(5000);
String s = momsSavings.toString();
// Sets s to "BankAccount[balance=5000]"
Overriding the equals Method
Equals tests for equal contents


Define the equals method to test whether two objects have equal state
When redefining equals method, you cannot change object signature; use a cast instead:
public class Coin
{
. . .
public boolean equals(Object otherObject)
{
Coin other = (Coin) otherObject;
return name.equals(other.name) && value ==
other.value;
}
. . .
}
You should also override the hashCode method so that equal objects have the same hash code
Should the call x.equals(x) always return true?
Answer: It certainly should – unless, of course, x is null.
Can you implement equals in terms of toString? Should you?
Answer:
If
toString
returns a string that describes all
instance fields, you can simply call
toString
on the implicit
and explicit parameters, and compare the results. However,
comparing the fields is more efficient than converting them into
strings.
Overriding the clone Method
Copying an object reference gives two references to same object
BankAccount account2 = account;
Sometimes, need to make a copy of the object

Define clone method to make new object (see Advanced Topic 10.6)
Use clone:
BankAccount clonedAccount = (BankAccount)account.clone();
Must cast return value because return type is Object
Creates shallow copies

Does not systematically clone all subobjects
Must be used with caution
It is declared as protected; prevents from accidentally calling x.clone() if the class to which x belongs hasn't redefined clone to be public
You should override the clone method with care (see Advanced Topic 10.6)