previous |
start
Overriding the clone Method
- Copying object reference gives two references to same
object
BankAccount account2 = account1;
- Sometimes, need to make a copy of the object
- Use clone:
BankAccount account2 =
(BankAccount)account1.clone();
- Must cast return value because return type is
Object
- Define clone method to make new object:
public Object clone()
{
BankAccount cloned = new BankAccount();
cloned.balance = balance;
return cloned;
}
- Warning: This approach doesn't work with inheritance--see
Advanced Topic 11.6
previous |
start