码迷,mamicode.com
首页 > 其他好文 > 详细

Object_clone

时间:2018-08-24 00:27:54      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:getc   pre   方法   垃圾回收   not   创建   调用   pac   tag   

clone

  • 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());
    }
}

 

Object_clone

标签:getc   pre   方法   垃圾回收   not   创建   调用   pac   tag   

原文地址:https://www.cnblogs.com/yu-zhi/p/9527155.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!