对于我的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
Run Code Online (Sandbox Code Playgroud)
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();
}
Run Code Online (Sandbox Code Playgroud)
我发布了我认为与节省空间相关的所有代码.如果问题很难找到,我可以发布每一行.请告诉我.
有一个额外<Thing>的东西让编译器感到困惑.更改
public class Bag<Thing> implements Container<Thing> {
Run Code Online (Sandbox Code Playgroud)
至
public class Bag implements Container<Thing> {
Run Code Online (Sandbox Code Playgroud)
现在你正在创建一个新的变量类型命名Thing是隐藏在现有Thing接口.你现在写的是等同于
public class Bag<E> implements Container<E>
Run Code Online (Sandbox Code Playgroud)
...只是用一个名为Thing而不是的变量E.
| 归档时间: |
|
| 查看次数: |
375 次 |
| 最近记录: |