Making a Copy of Object

  1. A copy of an object is a second object containing identical information as the first.

    Example:

    The object referenced by MyVariable is an exact copy of the object referenced by harrysChecking (all the instance variables have the same value).

  2. How you can create an identical copy of a BankAccount object:


    Example:
       BankAccount harrysChecking = new BankAccount();
       BankAccount myVariable;
    
       myVariable = new BankAccount(harrysChecking.getBalance());  // Copy
    

  3. Effect of copying:


    Example:
      myVariable.deposit(1000);   
                   // adds 1000 to myVariable.balance
                   // DOES NOT add 1000 to harrysChecking.balance !
    

 

 


Copy Constructor

  1. We have seen:


    Making a copy of a BankAccount object:
       BankAccount harrysChecking = new BankAccount();
       BankAccount myVariable;
    
       myVariable = new BankAccount(harrysChecking.getBalance() );  // Copy
    

  2. It would be nice if we could write:


    BankAccount harrysChecking = new BankAccount(); BankAccount myVariable; myVariable = new BankAccount(harrysChecking); // Copy

  3. It is possible... but we will have to extend the BankAccount class.

    Question: what do we have to add to the BankAccount class to allow use to write:


    BankAccount myVariable = new BankAccount(harrysChecking);

  4. Answer.....


    public class BankAccount { private double balance; // *********************************************** // Constructor 1: does not take any parameters // *********************************************** public BankAccount() { balance = 0.0; } // ********************************************************* // Constructor 2: take a double representing initial deposit // ********************************************************* public BankAccount(double initialBalance) { balance = initialBalance; } // ********************************************************* // NEW Constructor: take a BankAccount object as parameter ! // ********************************************************* public BankAccount(BankAccount x) { balance = x.balance; // We can access x.balance directly !!! } public void deposit(double amount) { balance = balance + amount; } public void withdraw(double amount) { if ( amount <= balance ) balance = balance - amount; else System.out.println("**** Insufficient funds to withdraw $" + amount); } public double getBalance() { return(balance); } }

    Such a constructor is called Copy constructor (because they are used to make copies of objects).

  5. Demo programs: