Java Generic Class无法查找方法

时间:2016-02-16 19:15:23

标签: java

对于我的CS分配,我需要编写一个实现容器接口的通用Bag对象。 Bag应该只能容纳实现Thing界面的项目。我的问题是,当我尝试编译时,我得到了这个......

Bag.java:23: error: cannot find symbol
    if (thing.getMass() + weight >= maxWeight) {
symbol:   method getMass()
location: variable thing of type Thing
where thing is a type-variable:
  Thing extends Object declared in class Bag

getMass()方法在Thing界面中有明确定义,但我找不到Bag对象。这是我的班级文件......

public interface Thing {
    public double getMass();
}

public class Bag<Thing> implements Container<Thing> {
    private ArrayList<Thing> things = new ArrayList<Thing>();
    private double maxWeight = 0.0;
    private double weight = 0.0;

    public void create(double maxCapacity) {
    maxWeight = maxCapacity;
    }

    public void insert(Thing thing) throws OutOfSpaceException {
        if (thing.getMass() + weight >= maxWeight) {
            things.add(thing);
            weight += thing.getMass();
        } else {
            throw new OutOfSpaceException();
        }
    }
}

public interface Container<E> {
  public void create(double maxCapacity);
  public void insert(E thing) throws OutOfSpaceException;
  public E remove() throws EmptyContainerException;
  public double getMass();
  public double getRemainingCapacity();
  public String toString();
}

我发布了我认为与节省空间相关的所有代码。如果问题很难找到,我可以发布每一行。请告诉我。

1 个答案:

答案 0 :(得分:8)

还有一个额外的<Thing>让编译器感到困惑。变化

public class Bag<Thing> implements Container<Thing> {

public class Bag implements Container<Thing> {

现在,您正在创建名为Thing新类型变量隐藏现有的Thing界面。你现在写的东西相当于

public class Bag<E> implements Container<E> 

...只是使用名为Thing而非E的变量。