代码中的问题是我们不能直接调用Item类型的抽象方法clone,并且我不想修改Item类。有没有办法,或者我应该改变我的逻辑?
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 abstract Item clone();
}
class Tool extends Item {
protected double durability;
public Tool()
{
super("", false);
this.durability = 0;
}
public Tool(Tool src)
{
this.durability = src.durability;
}
public Item clone() throws CloneNotSupportedException {
Object obj = super.clone(); //problem is here
return (Item) obj;
}
}发布于 2018-04-18 11:31:12
不知何故,我消除了你的错误
编辑
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, boolean check ) {
this.name = name;
this.stackable = check;
}
@Override
public abstract Item clone() throws CloneNotSupportedException;
}
class Tool extends Item {
protected double durability;
public Tool()
{
super("", false);
this.durability = 0;
}
public Tool(Tool src)
{
this.durability = src.durability;
}
@Override
public Item clone() throws CloneNotSupportedException {
Item obj = (Item) this.clone();
return (Item) obj;
}
}发布于 2018-04-18 11:29:02
使用Cloneable接口实现工具类并覆盖clone()
发布于 2018-04-18 11:57:34
public class Example {
public static void main(String[] args) throws CloneNotSupportedException {
Tool t= new Tool();
System.out.println(t.hashCode());
Tool t1=(Tool) t.clone();
System.out.println(t1.hashCode());
}
}
abstract class Item{
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;
}
}
class Tool extends Item implements Cloneable {
protected double durability;
public Tool()
{
super();
this.durability = 0;
}
public Tool(Tool src)
{
this.durability = src.durability;
}
public Item clone() throws CloneNotSupportedException {
Object obj = super.clone(); //problem is here
return (Item) obj;
}
}https://stackoverflow.com/questions/49890604
复制相似问题