Java对象的浅克隆
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java对象的浅克隆相关的知识,希望对你有一定的参考价值。
/** * Java对象的浅克隆 * 在克隆对象时,如果对象的成员变量是基本类型,则使用浅克隆即可完成。 * 如果对象的成员变量包括可变引用类型,则需要深克隆 * 如果引用类型是不可变的,如String类,则不必进行深克隆 * 当需要克隆对象时,需要使用clone()方法,该方法将类中的各个域进行复制, * 如果对于引用类型的域,这种操作就会有问题,因此成为浅克隆。 * 提供克隆功能的类需要实现Cloneable接口,否则会抛出异常 */ public class Address{ private String state; private String province; private String city; public Address(String state, String province, String city) { this.state = state; this.province = province; this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } @Override public String toString() { return "Address [state=" + state + ", province=" + province + ", city=" + city + "]"; }
public class Employee implements Cloneable { private String name; private int age; //新增Address对象 private Address address; 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 Employee(String name, int age) { this.name = name; this.age = age; } public Employee(String name, int age, Address address) { this.name = name; this.age = age; this.address = address; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public Employee() { } @Override public String toString() { return "Employee [name=" + name + ", age=" + age + ", address=" + address + "]"; } //实现浅克隆 @Override protected Employee clone() throws CloneNotSupportedException { Employee emp = null; try { emp = (Employee) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return emp; } }
测试:
public class TestEmployeeAndAddress { public static void main(String[] args) throws CloneNotSupportedException { System.out.println("克隆之前:"); Address address = new Address("中国", "吉林", "长春"); Employee emp1 = new Employee("张XX",30,address); System.out.println("员工1的信息:"+emp1); System.out.println("克隆之后:"); Employee emp2 = emp1.clone(); emp2.getAddress().setState("中国"); emp2.getAddress().setProvince("四川"); emp2.getAddress().setCity("成都"); emp2.setName("李XX"); emp2.setAge(24); System.out.println("员工1的信息:"+emp1); System.out.println("员工2的信息:"+emp2); } }
结果如下:
本文出自 “IT菜鸟” 博客,请务必保留此出处http://mazongfei.blog.51cto.com/3174958/1907844
以上是关于Java对象的浅克隆的主要内容,如果未能解决你的问题,请参考以下文章