一、创建对象的四种方法:

  a. new语句;

  b. 利用反射,调用描述类的Class对象的newInstance()实例方法;

  c. 调用对象的clone();

  d. 反序列化;

  其中new 和 newInstance()会调用类的构造方法,而clone()和反序列化不会;

 

Cloneable接口:

  Cloneable接口里没有定义方法,仅用于标记对象,clone()方法是Object类里面的方法,是一个protected native方法;

  如果对象实现Cloneable接口的话,需要覆盖clone方法;

  浅拷贝:只复制基本类型;

public class Person implements Cloneable{  
      
    private int age ;  
    private String name;  
      
    public Person(int age, String name) {  
        this.age = age;  
        this.name = name;  
    }  
      
    public Person() {}  
  
    public int getAge() {  
        return age;  
    }  
  
    public String getName() {  
        return name;  
    }  
      
    @Override  
    protected Object clone() throws CloneNotSupportedException {  
        return (Person)super.clone();  
    }  
}  
View Code

相关文章:

  • 2021-11-08
  • 2021-12-14
  • 2021-11-28
  • 2021-05-14
  • 2021-10-13
  • 2021-07-25
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-12-21
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-22
  • 2022-02-28
相关资源
相似解决方案