日期:2014-05-19 浏览次数:20966 次
class Address{ public Address(){ } public Address(String state, int number){ this.number = number; this.state = state; } @Override public String toString(){ return "state: " + state + " munber: " + number; } public String getState(){ return state; } public void setState(String state){ this.state = state; } public int getNumber(){ return number; } public void setNumber(int number){ this.number = number; } private String state; private int number; } public class Employee implements Cloneable{ public Employee(){ } public Employee(String name, int age, Address address){ this.address = address; this.age = age; this.name = name; } public String getName(){ return name; } public void setName(String name){ this.name = name; } public int getAge(){ return age; } public void setAge(int age){ this.age = age; } public Address getAddress(){ return address; } public void setAddress(Address address){ this.address = address; } @Override public String toString(){ StringBuilder sb = new StringBuilder(); sb.append("name:" + name + ", "); sb.append("age:" + age + " \n"); sb.append("Address: " + address); return sb.toString(); } @Override protected Employee clone(){ Employee employee = null; try{ employee = (Employee) super.clone(); }catch(CloneNotSupportedException e){ e.printStackTrace(); } return employee; } private String name; private int age; private Address address; public static void main(String[] args){ System.out.println("克隆之前:"); Address add1 = new Address("中国", 1); Employee emp1 = new Employee("rollen", 20, add1); System.out.println(emp1); System.out.println("克隆之后"); Employee emp2 = emp1.clone(); System.out.println("====重新设置对象emp2值====="); emp2.setName("hello world"); emp2.setAge(100); //emp2.address.setNumber(2);// //emp2.address.setState("美国");//原始类的赋值方法 emp2.setAddress(new Address("美国", 2));//本类中的set方法#### System.out.println(emp1); System.out.println("-----"); System.out.println(emp2); } }