-----------------------原话-----------------------
在Object类中,clone方法被声明为protected,因此无法直接调用anObject.clone()。
-----------------------------------------------------
这句话是什么意思啊 不是说protected方法的话 子类和同一个包里的类就可以使用吗
我想那个anObject就是子类吧 为什么无法直接调用呢?
在Object类中,clone方法被声明为protected,因此无法直接调用anObject.clone()。
-----------------------------------------------------
这句话是什么意思啊 不是说protected方法的话 子类和同一个包里的类就可以使用吗
我想那个anObject就是子类吧 为什么无法直接调用呢?
给你个例子:package com.dai;public class CloneTest {
public static void main(String[] args) throws Exception{
Student student = new Student();
student.setAge(20);
student.setName("zhangsan");
Student student1 = (Student)student.clone();
System.out.println(student1.getAge());
System.out.println(student1.getName());
System.out.println(student == student1);
student1.setName("lisi");
System.out.println(student.getName());
System.out.println(student1.getName());
}
}
class Student implements Cloneable{
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
}
返回:
此实例的一个克隆。
抛出:
CloneNotSupportedException - 如果对象的类不支持 Cloneable 接口,则重写 clone 方法的子类也会抛出此异常,以指示无法克隆某个实例。
// Object 类本身不实现接口 Cloneable,
//所以在类为 Object 的对象上调用 clone 方法将会导致在运行时抛出异常
public class TestClone {
public static void main(String[] args) {
new SubClass().clone();
}
}class SubClass implements Cloneable {//子类实现接口Cloneable
public Object clone() {
SubClass subClass = null;
try {
System.out.println("你正在调用clone()方法");
subClass = (SubClass) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return subClass;
}
}
/*output:
你正在调用clone()方法
*/