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

后端 未结 8 1255
孤街浪徒
孤街浪徒 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:07

    The JVM is able to clone the object for you, and you're thus not supposed to construct a new person by yourself. Just use this code:

    class Person implements Cloneable {
        // ...
        @Override
        public Object clone() throws CloneNotSupportedException {
            return super.clone();
        }
    }
    

    or

    class Person implements Cloneable {
        // ...
        @Override
        public Object clone() {
            try {
                return super.clone();
            }
            catch (CloneNotSupportedException e) {
                throw new Error("Something impossible just happened");
            }
        }
    }
    

    This will work even if the Person class is subclassed, whereas your clone implementation will always create an instance of Person (and not an instance of Employee for an Employee, for example).

提交回复
热议问题