2013-02-20 35 views
-4

我不知道如何解决这个问题。这里是我的代码:接口引用

public interface Stuff { 
    public String description(); 
    public double weight(); 
} 

class Bag implements Stuff { 
    public String description() { 
     return "bag of"; 
    } 
    public double weight() { 
     return 10.50; 
    } 
} 

class StuffWrapper implements Stuff { 

    Stuff item; 

    public StuffWrapper(Stuff item) { 
     this.item = item; 
    } 

    public String description() { 
     return item.description(); 
    } 

    public double weight() { 
     return item.weight(); 
    } 
} 

class Material extends StuffWrapper { 

    String material; 
    double weight; 

    public Material(Stuff item, String material, double weight) { 
     super(item); 
     this.material = material; 
     this.weight = weight; 
    } 

    public String description() { 
     return item.description() + " :" + material+ ":"; 
    } 

    public double weight() { 
     return item.weight() + weight; 
    } 
} 

,然后我有这样的:

Stuff icStuff = new Bag(); 
icStuff = new Material(icStuff, "leather", 10.30); 
icStuff = new Material(icStuff, "plastic", 20.50); 
System.out.println(icStuff.description() + Double.toString(icStuff.weight())); 

其输出

bag of :leather: :plastic:41.3 

做所有的,如果我想icStuff不再引用此之后:

icStuff = new Material(icStuff, "plastic", 20.50); 

我应该怎么做?

+1

你想什么指针指向? – 2013-02-20 23:08:21

+0

[Remove a variable memory]可能的重复(http://stackoverflow.com/questions/10536854/remove-a-variable-memory) – 2013-02-20 23:10:11

+0

你的'Bag'实现没有意义。另外,你重新分配'icStuff'而不用它们之间;这不可能是你想要的。您是否打算*将商品添加到包中? – dasblinkenlight 2013-02-20 23:11:23

回答

2

将其分配给别的东西,或为空,或任何你想让它引用

icStuff = null; 
icStuff = Somethingelse;