In fact, all Java objects can be cloned, but because they are set as a retained method (protected) in the basic class object, to truly possess the cloning capability, You need to implement the cloneable interface, rewrite the clone method. The object obtained by cloning is a local copy.
Sample Code:
Class user implements cloneable {
Int age;
Public user (INT age ){
// Use the this keyword to avoid confusion between class member variables and shape parameters.
This. Age = age;
}
// You can add @ override or not here. If you add @ override, the system will automatically prompt whether it is correct.
@ Override
Public object clone {
Object o = NULL;
Try {
O = super. Clone ();
} Catch (clonenotsupportedexception e ){
E. printstacktrace ();
}
}
Public String tostring (){
Return integer. tostring (this. Age );
}
}
Public class test {
// (1) the static method can only be called in main (2) modifying the passed user object
Static user g (User U ){
U. Age ++;
Return U;
}
// A copy of the user object is generated locally
Static user F (User U ){
U = (User) U. Clone ();
U. Age ++;
Return U;
}
Public static void main (string [] ARGs ){
User u = new user (23 );
User U2 = g (U );
If (u = u2)
System. Out. println ("u = u2 ");
Else
System. Out. println ("u! = U2 ");
// The tostring () method of the user object is automatically called below
System. Out. println ("U. Age:" + U );
System. Out. println ("u2.age:" + U2 );
User U3 = new user (23 );
User U4 = f (U3 );
If (U3 = U4)
System. Out. println ("U3 = U4 ");
Else
System. Out. println ("U3! = U4 ");
System. Out. println ("u3.age:" + U3 );
System. Out. println ("u4.age:" + U4 );
}
}
// Basic Knowledge: to make the object have a clone method, you only need to implement the cloneable interface and rewrite the clone method. However, there are two points to note: (1) Call super. clone () method (2) is defined as public Method
/** -- Note --**/
The above code is written in the text editor and may be omitted.