|
||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | |||||||||
java.lang.Objecttips.cloneTest.CloneTest
This example demonstrates the use of the clone() method. The default representation
of clone() will create a new object without calling any contructors. The attributes
of the object will then be copied across to the new object. If in the case of primatives the attributes
are copied by value. In the case of objects the references are copied by value. The objects themselves are
not copied and the result of clone() will mean that they have two references pointing to them.
Overriding clone allows you to change all that by creating new object and managing the return value yourself.
For example:
The output of this program without overriding clone is:
First Object Age: 10
15/6/2004
Random Number is: 0.659720135566651
First Object Age: 10
12/4/1989
Random Number is: 0.659720135566651
First Object Fred Age: 10
12/4/1989
Random Number is: 0.659720135566651
By uncommenting the clone method we can change the output to:
First Object Age: 10
15/6/2004
Random Number is: 0.5056783284208972
First Object Age: 10
12/4/1989
Random Number is: 0.5056783284208972
MyClone Age: 24
21/3/1961
Random Number is: 0.13724087984367472
| Field Summary | |
private java.util.GregorianCalendar |
aDate
|
private int |
age
|
private RandNum |
aRandNum
|
private java.lang.String |
name
|
| Constructor Summary | |
CloneTest(java.lang.String newLabel)
Constructor that creates an object - with a label |
|
| Method Summary | |
java.lang.Object |
clone()
Find out what happens when you overload clone. |
static void |
main(java.lang.String[] args)
The main method demonstrating what clone does in this case |
(package private) void |
print()
Prints out the contents of the object on the console |
(package private) void |
setAge(int age)
Set the age to a new value |
(package private) void |
setDate(int Year,
int Month,
int Date)
Set the date to a new value |
java.lang.String |
toString()
Override toString to printout the label for Debug purposes |
| Methods inherited from class java.lang.Object |
equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Field Detail |
private java.lang.String name
private int age
private java.util.GregorianCalendar aDate
private RandNum aRandNum
| Constructor Detail |
public CloneTest(java.lang.String newLabel)
| Method Detail |
public java.lang.String toString()
void setDate(int Year,
int Month,
int Date)
Year - The new year valueMonth - The new month valueDate - The daya of the month value
nonevoid setAge(int age)
age - The age in yearsvoid print()
public java.lang.Object clone()
public static void main(java.lang.String[] args)
throws java.lang.Exception
java.lang.Exception
|
||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | |||||||||