首页» JAVA »Java-引用类型的克隆(clone)

Java-引用类型的克隆(clone)

立即注册PayPal并开始接受信用卡付款。
转载请保持文章完整性!
本文链接地址:http://blog.desizen.com/4lone/222.html
主页:joel's blog

引用类型的克隆,得先实现了cloneable接口,声明为可以进行克隆,然后再进行克隆

class StringTest
{	
	public static void main(String[] args)
	{
 
		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);
	}
}
 
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;
	}
}
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()
	{
		//Object o=null;
		Student o=null;
		try
		{
			o=(Student)super.clone();
		}
		catch(CloneNotSupportedException e)
		{
			System.out.println(e.toString());
		}
		o.p=(Professor)p.clone();
		return o;
	}
}

标签:

与"Java-引用类型的克隆(clone)"相关的文章:

没有评论 »

还没有评论呢。

留下评论

emoticons

Feedback Form