깊이 복사 실례 (한 클래스에 다른 클래스를 포함하는 대상)

6417 단어
import java.util.*;

/**
 *  
 * 
 */
public class test {
    public static void main(String[] args){
        String name = " ";
        int age = 15;
        Address ads = new Address();
        ads.setAddress(" ");
        Student stu1 = new Student(name,age,ads);
        Student stu2 = stu1.clone();

        ads.setAddress(" ");
        System.out.println(" 1 :"+stu1.getName()+"  :"+stu1.getAge()+"  :"+stu1.getAds().getAddress());
        System.out.println(" 2 :"+stu2.getName()+"  :"+stu2.getAge()+"  :"+stu2.getAds().getAddress());
    }
}

// 
class Address implements Cloneable{
    private String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public Object clone(){
        Address address = null;
        try {
            address = (Address) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return address;
    }
}


// 
class Student implements Cloneable{
    private String name;
    private int age;
    private Address ads;

    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;
    }

    public Address getAds() {
        return ads;
    }

    public void setAds(Address ads) {
        this.ads = ads;
    }

    public Student(String name, int age, Address ads){
        this.name = name;
        this.age = age;
        this.ads = ads;
    }

    @Override
    public Student clone(){
        Student stu = null;
        try {
            stu = (Student) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        stu.ads = (Address) ads.clone();
        return stu;
    }
}


 :

 1 :   :15  : 
 2 :   :15  : 

 2 ,  。
 

좋은 웹페이지 즐겨찾기