ITeye博客

深拷贝问题

lianggl2008 · 2010-03-14 21:50 · 编程语言 · Markdown

public class CopyObject {

	/**
	 * @param
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Professor p = new Professor("wangwu", 50);
		Student s1 = new Student("zhangsan", 18, p);
		Student s2 = (Student) s1.clone();
		s2.p.name = "lisi";
		s2.p.age = 30;
		System.out.println("name=" + s1.p.name + "," + "age=" + s1.p.age);
		System.out.println("name=" + s2.p.name + "," + "age=" + s2.p.age);
	}

}

class Student implements Cloneable {
	String name;

	int age;

	Professor p;

	Student(String name, int age, Professor p) {
		this.name = name;
		this.age = age;
		this.p = p;
	}

	public Object clone() {
		Student o = null;
		try {
			o = (Student) super.clone();
		} catch (CloneNotSupportedException e) {
			System.out.println(e.toString());
		}
		o.p = (Professor) p.clone();
		return o;
	}
}

class Professor implements Cloneable {
	String name;

	int age;

	Professor(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public Object clone() {
		Object o = null;
		try {
			o = super.clone();
		} catch (CloneNotSupportedException e) {
			System.out.println(e.toString());
		}
		return o;
	}
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。