Java Reference
In-Depth Information
472
Implementing the clone method is quite a bit more difficult than implementing
the toString or equals methodsȌsee Advanced Topic 10.6 for details.
Let us suppose that someone has implemented the clone method for the
BankAccount class. Here is how to call it:
BankAccount clonedAccount = (BankAccount)
account.clone();
The return type of the clone method is the class Object . When you call the
method, you must use a cast to convince the compiler that account.clone()
really has the same type as clonedAccount .
C OMMON E RROR 10.7: Forgetting to Clone
In Java, object fields contain references to objects, not actual objects. This can
be convenient for giving two names to the same object:
BankAccount harrysChecking = new BankAccount();
BankAccount slushFund = harrysChecking;
// Use HarryȐs checking account for the slush fund
slushFund.deposit(80000)
// A lot of money ends up in HarryȐs checking account
However, if you don't intend two references to refer to the same object, then this
is a problem. In that case, you should use the clone method:
BankAccount slushFund = (BankAccount)
harrysChecking.clone();
Q UALITY T IP 10.1: Clone Mutable Instance Fields in
Accessor Methods
Consider the following class:
public class Customer
{
public Customer(String aName)
{
name = aName;
account = new BankAccount();
Search WWH ::




Custom Search