/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package test;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author huanghuankun
*/
public class CloneTest {
public static class User implements Cloneable {//要设置为static类型,否则在static类型的main方法中不能引用
String name;//引用类型
int age;//primitive类型
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public static class CloneUser implements Cloneable {//继承Cloneable接口
User user;
long balance;
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public static void main(String[] args) {
User user = new User();
user.name = "huanghuankun";
user.age = 25;
CloneUser quoteUser = new CloneUser();
quoteUser.user = user;//直接引用
quoteUser.balance = 10000;
try {
CloneUser cloneUser = (CloneUser) quoteUser.clone();
if (quoteUser.balance == cloneUser.balance) {
System.out.println("因为balance是primitive类型,所以clone对象和原型是独立且相等的。");
}
quoteUser.balance = 20000;
if (quoteUser.balance == cloneUser.balance) {
System.out.println("改变任何primitive类型,不会影响原型的值");
}
if (quoteUser.user == cloneUser.user && quoteUser.user.equals(cloneUser.user)) {
System.out.println("因为user是引用型对象,所以克隆对象的引用类型和原型对象的引用类型相等");
}
quoteUser.user.age = 24;
if (cloneUser.user.age == 24) {
System.out.println("所以改变引用类型的值,克隆对象和原型都会改变。");
}
User copyUser = (User)user.clone();
copyUser.name = "huanghunkun1";
if (!quoteUser.user.name.equals("huanghuankun1")) {
System.out.println("String虽然是引用类型,但也是是不可改变类型,不能通过浅copy的方法来改变其值。");
}
} catch (CloneNotSupportedException ex) {
Logger.getLogger(CloneTest.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Clone出现异常");
}
}
}
输出结果:
因为balance是primitive类型,所以clone对象和原型是独立且相等的。
因为user是引用型对象,所以克隆对象的引用类型和原型对象的引用类型相等
所以改变引用类型的值,克隆对象和原型都会改变。
String虽然是引用类型,但也是是不可改变类型,不能通过浅copy的方法来改变其值。
本文通过实例演示了Java中克隆机制的工作原理,特别是对于基本类型和引用类型的区别处理。展示了如何实现Cloneable接口并使用clone方法进行对象复制,同时讨论了浅拷贝和深拷贝的概念。
170

被折叠的 条评论
为什么被折叠?



