How to clone a Java object with the clone() method

后端 未结 8 1253
孤街浪徒
孤街浪徒 2020-12-20 11:29

I don\'t understand the mechanism of cloning custom object. For example:

public class Main{

    public static void main(String [] args) {

        Person pe         


        
相关标签:
8条回答
  • 2020-12-20 12:21

    There's no need to create the object explicitly here in clone() method. Just by calling super.clone() will create the copy of this object. It will perform the shallow clone.

    0 讨论(0)
  • 2020-12-20 12:24

    It's the same purpose as any such interface. Primarily it allows methods (etc.) to accept ANY Clonable object and have access to the method they need without limiting themselves to one specific object. Admittedly Clonable is probably one of the less useful interfaces in this respect, but there's certainly places where you might want it. If you want more of an idea consider the interface Comparable which for example allows you to have sorted lists (because the list doesn't need to know what the object is, only that they can be compared).

    0 讨论(0)
提交回复
热议问题