有一些东西不适合Cloneable接口

时间:2018-04-07 04:59:58

标签: java

public class Tool extends Item {
    @Override
    public Item clone() throws CloneNotSupportedException
    {
        return super.clone();
    }
}

clone()方法给了我一个错误:

  

无法直接为类型Item

调用抽象方法clone()

Item类是一个实现Cloneable接口的抽象类。

1 个答案:

答案 0 :(得分:1)

public class CloneTest {

    static abstract class Item implements Cloneable {
        private boolean stackable;

        protected String name;

        public Item() {
            this.name = new String("Air");
            this.stackable = true;
        }

        public Item(String name) {
            this.name = name;
            this.stackable = true;
        }

        public Item(String name, boolean stackable) {
            this.name = name;
            this.stackable = stackable;
        }

        public String getName() {
            return this.name;
        }

        public void setName(String n) {
            this.name = n;
        }

        @Override
        public boolean equals(Object rhs) {
            Item r = (Item) rhs;

            return (this.name).equals(r.name);
        }

        @Override
        public int hashCode() {
            return this.name.hashCode();
        }

        public boolean isStackable() {
            return this.stackable;
        }

        public abstract void read(Scanner s);

        @Override
        public Item clone() throws CloneNotSupportedException {
           Object obj = super.clone();
           // Add some custom logic here... like initializing few members
           return (Item) obj;
        }

        @Override
        public String toString() {
            return (" " + this.name);
        }
    }

    public static class Tool extends Item {

        @Override
        public Item clone() throws CloneNotSupportedException {
            return super.clone();
        }

        @Override
        public void read(Scanner s) {

        }
    }

    public static void main(String[] args) throws CloneNotSupportedException 
{
        Tool tool1 = new Tool();
        System.out.println(tool1);
        Object tool2 = tool1.clone();
        System.out.println(tool2);
        System.out.println(tool1 == tool2);
    }
}