今天复习到 Object 类常用的方法, 老师对 clone() 方法一带而过, 于是自己写了点代码试验了一下, 做个挖坑记录.
? 代码 0.1
public class APITest {public static void main(String[] args) {TestClass t1 = new TestClass();TestClass t2 = t1.clone();}
}class TestClass {private String name;
}
IDE 提示 t1.clone() 处有错误
'clone()' has protected access in 'java.lang.Object'
思考了一下, 所有的类都继承 Object 类, 理应都继承了 clone() 方法才是
不过既然这里提示是 t1.clone() 无法访问, 那我不妨在 TestClass 中重写
? 代码 0.2
public class APITest {public static void main(String[] args) {TestClass t1 = new TestClass();try {TestClass t2 = (TestClass) t1.clone();} catch (CloneNotSupportedException e) {e.printStackTrace();}}
}class TestClass {private String name;@Overrideprotected Object clone() throws CloneNotSupportedException {return super.clone();}
}
所做改动
* TestClass 重写 Object 类中的 clone() 方法
* main() 方法中对 clone() 方法做异常处理
* t1.clone() 加向下转型
此时不报编译错误了, 尝试执行, 运行报错
java.lang.CloneNotSupportedException: TestClass
at java.lang.Object.clone(Native Method)
at TestClass.clone(APITest.java:18)
at APITest.main(APITest.java:6)
网络搜索下, 有文章提到要实现 Cloneable 接口
? 代码 1.0
public class APITest {public static void main(String[] args) {TestClass t1 = new TestClass();try {TestClass t2 = (TestClass) t1.clone();System.out.println(t1 == t2);System.out.println(t1.getClass() == t2.getClass());} catch (CloneNotSupportedException e) {e.printStackTrace();}}
}class TestClass implements Cloneable{private String name;@Overrideprotected Object clone() throws CloneNotSupportedException {return super.clone();}
}
至此问题解决
可以看到 clone() 的效果, t1 和 t2 指向不同的内存地址; t1 和 t2 运行时类相同.