[英]Java Generic Class Can't Find Method
对于我的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();
}
我发布了我认为与节省空间相关的所有代码。 如果问题很难找到,我可以发布每一行。 请告诉我。
还有一个额外的<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
的变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.