Object_clone

clonenode

  • protected Object clone() throws CloneNotSupportedException
    • 通常状况下,要clone方法须要抛出异常
    • 建立并返回此对象的一个副本
    • x.clone() != x
      • 也就是说是不一样的对象,复制的对象与原来的对象是一个不一样的对象
    • x.clone().getClass() == x.getClass()
      • 说明是同一个类
  • Cloneable接口
    • 在clone方法所在类中须要实现这个接口,由于这个接口是复制的标志接口
    • 记住: 这个接口没有构造方法与成员方法
package cn.itcast_04; public class Student4 implements Cloneable { private String name; private int age; public Student4() { super(); } public Student4(String name, int age) {
     //调用是Object构造方法    
super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } //重写clone()方法重写 @Override protected Object clone() throws CloneNotSupportedException { return super
.clone(); } }







 

package cn.itcast_04; /* *protected void finalize();当垃圾回收器肯定不存在对象有更多引用时候,垃圾回收器调用此方法 *可是何时调用该方法不知道 * *proected Object clone();建立而且返回该对象的副本 * A:重写该方法; * * Cloneabel;此类实现了Cloneable 接口,以指示Object.clone()方法对对象复制 换句话说,只有实现该接口,才能复制对象 Cloneable 是标志接口,里面没有方法,只有继承该方法才能克隆对象 */
 
public class StudentDemo4 { public static void main(String[] args) throws CloneNotSupportedException { //建立学生对象
        Student4 s = new Student4(); s.setName("liqingxiang"); s.setAge(24); Object obj = s.clone(); Student4 s2 = (Student4)obj; System.out.println("name:" + s.getName() + ",  age:" +s.getAge()); System.out.println("name:" + s2.getName() + ",  age:" +s2.getAge()); System.out.println("=============="); //s对象改变,可是s2对象属性没变,所以他们是两个不一样的对象
        s.setAge(29); s.setName("xiaoming"); System.out.println("name:" + s2.getName() + ",  age:" +s2.getAge()); } }
本站公众号
   欢迎关注本站公众号,获取更多信息