1. clone()为什么用protected修饰符修饰,而不是public
Object类中clone()方法声明为protected是一种保护机制,他的目的是在类中未重写Object的clone()方法的情况下,只能在本类里才能“克隆”本类的对象。下面我用程序对比仔细解释说明一下
public class User implements Cloneable {
public static void main(String[] args) {
User u =new User();
try {
u.clone(); //编译通过
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
public class Test {
public static void main(String[] args) {
User u =new User();
u.clone(); //编译错误,报错信息The method clone() from the type Object is not visible
}
}
Test类无法调用User类从父类Object继承来的clone()方法。User类自身可以调用。验证了一开始说的通过声明protected,只能保证自身才能克隆自身的实例对象(User类中才能克隆User对象,Test类不行)下面我们在来看一组代码。
public class User implements Cloneable {
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
public static void main(String[] args) {
User u