BankAccount Class Copy Constructor
UML as shown below
+--------------------------------------
+ BankAccount
+--------------------------------------
- balance: double
+--------------------------------------
+ BankAccount(startBalance:double)
+ BankAccount(anotherAccount: BankAccount)
+ toString(): String
CSCI-185 Prof. M. Kadri
Page 2 of 5
+--------------------------------------
Add a copy constructor to the BankAccount class. This constructor
should accept a
BankAccount object as an argument. It should assign to the balance
field the value in
the argument's balance field. As a result, the new object will be a
copy of the argument
object.
Write a driver program to demonstrate that your copy constructor
works. How?
BankAccount.java
public class BankAccount {
// Data member
private double balance;
// Constructor to initialize balance
public BankAccount(double balance) {
this.balance = balance;
}
// Copy Constructor
public BankAccount(BankAccount ba) {
this.balance = ba.balance;
}
// This method return BankAccount details in string
format
public String toString() {
return "Balance: "+balance;
}
}
BankAccountTest.java
public class BankAccountTest {
public static void main(String[] args) {
// Create object of BankAccount by
passing balance
BankAccount ba1 = new
BankAccount(1500);
// Create object of BankAccount by
copy constructor
BankAccount ba2 = new
BankAccount(ba1);
// Print bankAccounts
System.out.println("Bank Account 1:
"+ba1);
System.out.println("Bank Account 2:
"+ba2);
}
}
OUTPUT
Get Answers For Free
Most questions answered within 1 hours.