首页 > 解决方案 > 为什么在java中克隆对象时出现运行时异常

问题描述

我正在尝试执行对象的浅克隆我的狗类有一个原始变量 i=10,还有一个指向对象 j=20 的引用变量,而且我将克隆方法定义为公共但是我得到了运行时错误在线程“主”java.lang.CloneNotSupportedException 中说异常

package com.objectclasscoding.practice;

import com.objectclasscoding.practice.Cat.Dog;

class Cat {
    int j;

    public Cat(int j) {

        this.j = j;
    }

    class Dog implements Cloneable {
        Cat c;
        int i;

        public Dog(Cat c, int i) {
            this.c = c;
            this.i = i;
        }

    }

    public Object clone() throws CloneNotSupportedException {
        return (Dog) super.clone();
    }
}

public class ShallowCloningDemo {

    public static void main(String[] args) throws CloneNotSupportedException {
        Cat c = new Cat(20);
        Dog d1 = c.new Dog(c, 10);
        System.out.println(d1.i + ".." + c.j);

        Dog d2 = (Dog) d1.c.clone();
        d1.i = 888;
        d1.c.j = 999;
        System.out.println(d2.i + ".." + d2.c.j);

    }

}

运行此代码后,我收到运行时错误消息Exception in thread "main" java.lang.CloneNotSupportedException

标签: java

解决方案


您似乎正在调用 clone ond1.c的一个实例Cat,它没有实现Cloneable

For some reason you've added a clone() method to Cat rather than Dog. Inside that method, you tried to cast the result to Dog, as if a cloned Cat would be an instance of Dog. That does not make sense. Cats are notoriously not the same as dogs.


推荐阅读