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 =new User();
try {
u.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class Test {
public static void main(String[] args) {
User u =new User();
try {
u.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
让User类重写父类Object中的克隆方法后,Test类也可以克隆User对象了。
结论
如果子类(User类)没有重写父类(Object)受保护的clone()方法,它使用的就是从父类Object继承来的clone()方法,由于Test类与Object类是不同包的关系,所以无法调用。也就是上面第一段代码展示的那样,报编译错误The method clone() from the type Object is not visible。如果子类User重写了clone方法,调用的就是子类中clone方法,子类User与Test在同一个包中,所以可以调用。