⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 clonetest.java

📁 一些Java写的测试API的源代码
💻 JAVA
字号:
/*
 *clone()
 *
 *Creates and returns a copy of this object. The precise meaning of "copy"
 *may depend on the class of the object. The general intent is that,for any 
 *object x, the expression:
 *x.clone() != x
 *will be true,and that the expression:
 *	x.clone().getClass() == x.getClass()
 *will be true,but these are not absolute requirements.While it is 
 *typically the case that:
 *	x.clone().equals(x)
 */
 

/*
 *String 类没有重写clone()方法;
 *String 对象是常量对象。				
 */
 
 class CloneTest
 {
 	
 	public static void main(String[] args)
 	{
 		Professor p = new Professor("zhang",45);
 		Student s1= new Student("miracle",21,p);
 		Student s2 = (Student)s1.clone();
 		/*
 		s2.name ="djb";
 		s2.age = 20;
 		System.out.println("name="+s1.name+":"+"age="+s1.age);*/
 		
 		s2.p.name="lisi";
 		s2.p.age = 30;
 		/*此时s2中的p没有复制一份,
 		 *要复制一份,可以在Professor中重写clone()*/
 		System.out.println("name="+s1.p.name+":"+"age="+s1.p.age);
 	}	
 	
 }
 
 class Professor 
 {
 	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.getMessage());
 		}
 		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.getMessage());
 		}
 		o.p = (Professor)p.clone();
 		return o;
 	}
 	
 }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -