Object: The Cosmic Superclass

All classes defined without an explicit extends clause automatically extend Object

Overriding the toString Method

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]"

"box=" + box;
// Result: "box=java.awt.Rectangle[x=5,y=10,width=20,height=30]"

public String toString()
{
   return "BankAccount[balance=" + balance + "]";
}

BankAccount momsSavings = new BankAccount(5000);
String s = momsSavings.toString();
// Sets s to "BankAccount[balance=5000]"

Overriding the equals Method

public class Coin
{
   . . .
   public boolean equals(Object otherObject)
   {
      Coin other = (Coin) otherObject;
      return name.equals(other.name) && value ==
         other.value;
   }
   . . .
}


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

BankAccount clonedAccount = (BankAccount)account.clone();