美文网首页
java基础之Clone

java基础之Clone

作者: writeanewworld | 来源:发表于2018-08-22 13:57 被阅读0次

    1.代码

    public class CloneTest{
    public static void main(String[] args) {
        Person p = new Person("一斤","两斤");
        System.out.println(p);
        
        Person p1 = p;
        System.out.println(p1);
        
        try {
            Person p2 = (Person) p.clone();
            System.out.println(p2);
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        
     }
    
    }
    
    class Person implements Cloneable{
    
    private String eat;
    private String drink;
    
    //new person 就是使用提供的重载的构造器进行实例化,默认的是使用无参构造器进行实例化
    Person(String eat,String drink){
        this.eat = eat;
        this.drink = drink;
    }
    
    
    public String getEat() {
        return eat;
    }
    public void setEat(String eat) {
        this.eat = eat;
    }
    public String getDrink() {
        return drink;
    }
    public void setDrink(String drink) {
        this.drink = drink;
    }
    
    @Override
    protected Object clone() throws CloneNotSupportedException {
        //clone有缺省行为,super先将父类中的成员复制到位,然后再复制自己的成员 
        return (Person )super.clone();
    }
    
    }
    

    2.运行结果

    com.begin21.top.Person@7852e922
    com.begin21.top.Person@7852e922
    com.begin21.top.Person@4e25154f
    

    相关文章

      网友评论

          本文标题:java基础之Clone

          本文链接:https://www.haomeiwen.com/subject/yizeiftx.html