简单的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(); } } }
上一篇: Lucene官方一个简单的实例