簡體   English   中英

Java Generic Class無法查找方法

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM