Java Reference
In-Depth Information
}
public String getName()
{
return name;
}
public BankAccount getAccount();
{
return account;
}
private String name;
private BankAccount account;
}
472
473
This class looks very boring and normal, but the getAccount method has a
curious property. It breaks encapsulation, because anyone can modify the object
state without going through the public interface:
Customer harry = new Customer(ÐHarry HandsomeÑ);
BankAccount account = harry.getAccount();
// Anyone can withdraw money!
account.withdraw(100000);
Maybe that wasn't what the designers of the class had in mind? Maybe they
wanted class users only to inspect the account? In such a situation, you should
clone the object reference:
public BankAccount getAccount();
{
return (BankAccount) account.clone();
}
Do you also need to clone the getName method? NoȌthat method returns a
string, and strings are immutable. It is safe to give out a reference to an
immutable object.
A DVANCED T OPIC 10.6: Implementing the clone
Method
The Object.clone method is the starting point for the clone methods in
your own classes. It creates a new object of the same type as the original object.
It also automatically copies the instance fields from the original object to the
Search WWH ::




Custom Search