In-depth shallow Java Clone technology (2)

zhaozj2021-02-16  144

In the previous one, the basic knowledge of Clone in Java is introduced. This article will focus on how to implement Clone.

l Clone implementation

1. Implement a Cloneable interface

Through the introduction of the previous article, we know that a class must have a Cloneable interface. To do this, Clone features have been basically achieved. Clone features For us, the most important thing is to be able to use it. So how can we use the clone function? The answer is to override the Object # clone () method.

2. Override Object # clone () method

Why do you need to override the Object # clone () method? It has to stand again from the JDK source code again. The prototype of the Object # clone () method in the JDK is:

Protected Native Object Clone () throws clonenotsupportedException;

Whether to note that here the clone () method modifier is protected instead of public. The invisibility of this access makes us not visible to the Object # clone () method. I believe that readers have understood why the object # clone () method is to overwrite. Moreover, the modifier of the covered method must be a public, and if it is still reserved as protected, the overlay will become no practical. Let's take a simple example of a Clone function:

/ *

* Examples of classes with Clone features

* /

Public Class CloneableObjexample Implements Cloneable {

// ... part of the code has omitted ...

Private string name = NULL;

Private int score = 0;

/ **

* Note: Change the protected modifier to public

* @see java.lang.Object # clone ()

* /

Public / * protected * / Object Clone () throws clonenotsupportedException {

// Call method of the parent class

Object result = super.clone ();

// Todo: Custom Clone data

Return Result;

}

}

3. Customize Clone

At this point, Clone has truthfully white. Clone objects we can customize it. Also on the example above. The following method has been enhanced to the function:

Public / * protected * / Object Clone () throws clonenotsupportedException {

// Call method of the parent class

CloneableObjexample Result = (CloneableObjexample) super.clone ();

// Todo: Custom Clone data

// Although "Clone" is, you can also do point adjustments

Result.name = "new name";

Result.score = 90;

Return Result;

}

This article introduces how to implement Clone. The next parameters will analyze the advanced features of Clone, etc. Clone, etc.

转载请注明原文地址:https://www.9cbs.com/read-8853.html

New Post(0)