|
Therefore:
|
Example:
|
Therefore:
|
|
|
|
b = a;
|
All it does is: make the reference variable b point to the same array:
|
public class CopyObject1
{
public static void main(String[] args)
{
BankAccount a = new BankAccount( ); // Object a
a.accNum = 123;
a.name = "John";
a.balance = 1000;
BankAccount b; // The copy
b = a; // is b a copy of a ??
/* ====================================
Let's do an experiment....
==================================== */
/* ----------------------------------
Print the values before the update
---------------------------------- */
System.out.println("Object a: " + a.convToString());
System.out.println("Object b: " + b.convToString());
b.accNum = 789; // Update the COPY
b.name = "Jess"; // (must NOT change the original)
b.balance = 5000; //
/* ----------------------------------
Print the values after the update
---------------------------------- */
System.out.println("Values after updating the copy b.balance:");
System.out.println("Object a: " + a.convToString());
System.out.println("Object b: " + b.convToString());
}
}
|
Output of this program:
Object a: Account number: 123, Name: John, Balance: 1000.0 Object b: Account number: 123, Name: John, Balance: 1000.0 Values after updating the copy b.balance: Object a: Account number: 789, Name: Jess, Balance: 5000.0 Object b: Account number: 789, Name: Jess, Balance: 5000.0 |
How to run the program:
|
Observation (conclusion from this experiment):
|
|
The solution is the same as the case of copying an attay:
|
public class CopyObject2
{
public static void main(String[] args)
{
BankAccount a = new BankAccount( ); // Object a
a.accNum = 123;
a.name = "John";
a.balance = 1000;
BankAccount b; // The copy
/* ==================================
How to copy an object in Java
================================== */
b = new BankAccount( ); // Create a new object
b.accNum = a.accNum; // Copy old values over
b.name = a.name; // to the new object
b.balance = a.balance;
/* ====================================
Let's do the experiment again....
==================================== */
/* ----------------------------------
Print the values before the update
---------------------------------- */
System.out.println("Object a: " + a.convToString());
System.out.println("Object b: " + b.convToString());
b.accNum = 789; // Update the COPY
b.name = "Jess"; // (must NOT change the original)
b.balance = 5000; //
/* ----------------------------------
Print the values after the update
---------------------------------- */
System.out.println("Values after updating the copy b.balance:");
System.out.println("Object a: " + a.convToString());
System.out.println("Object b: " + b.convToString());
}
}
|
How to run the program:
|