欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

简单的clone

程序员文章站 2022-05-31 12:23:53
...
class Programmer implements Cloneable{   
	 	private String name; //员工姓名
	    private int age; //员工年龄
	 	private double salary;	 //员工工资
	
	    /*构造方法*/
		 Programmer(String name,int age,double salary) { 
		this.name=name;   
		this.age=age;   
		this.salary=salary;   
	    }   
	
			public Object clone() throws CloneNotSupportedException{ //定义克隆方法
				Programmer p=(Programmer)super.clone(); //确定要复制的对象
				return p;   
			}  
		
		public static void main(String[] args) {   
			try {
				Programmer p1=new Programmer("Kevin ",25,2000);
				Programmer p2=(Programmer)p1.clone();                  //克隆的使用
				p2 .name=" Andy "; //修改p2的员工姓名
				p2.age=28;	         //修改p2的员工年龄
				p2.salary=3000;	     //修改p2的员工工资
				System.out.println("name="+p1.name+",  age="+p1.age+",  salary="+p1.salary); 
				System.out.println("name="+p2.name+",  age="+p2.age+",  salary="+p2.salary);   
			} catch(CloneNotSupportedException e) {   
				System.out.println("CloneNotSupportedException异常"+e. getMessage());
				e.printStackTrace();	   
			}
		 }
}