-----------------------原话-----------------------
在Object类中,clone方法被声明为protected,因此无法直接调用anObject.clone()。
-----------------------------------------------------
这句话是什么意思啊   不是说protected方法的话 子类和同一个包里的类就可以使用吗
我想那个anObject就是子类吧  为什么无法直接调用呢?

解决方案 »

  1.   

    Object 与你定义的AnObject没有在同一个包中的,所以即使你继承了Object 的clone()方法,在anObject的外面你是不能用anOjbect.clone().但是你可以在你的AnObject中用this.clone()或者super.clone(),定义自己的方法,在他们放在自己定义的方法的内部,然后就可以在外面使用了,当然你的类得实现Cloneable接口了,才能用clone()方法。
    给你个例子: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();
    }
    }
      

  2.   

    clone():
    返回:
    此实例的一个克隆。 
    抛出: 
    CloneNotSupportedException - 如果对象的类不支持 Cloneable 接口,则重写 clone 方法的子类也会抛出此异常,以指示无法克隆某个实例。
      

  3.   

    //只有实现了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()方法
    */