The Awesome Egg
The Awesome Egg

Reputation: 57

Java Generic Class Can't Find Method

For my CS assignment I need to write a generic Bag object that implements the container interface. The Bag should only be able to hold items that implement the Thing interface. My problem, is when I try to compile, I get the this...

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

the getMass() method is clearly defined in the Thing interface, but I can not get the Bag object to find it. Here are my class files...

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();
}

I posted all of my code that i feel is relevant to save space. If the problem is difficult to locate, i can post every line. Just let me know.

Upvotes: 3

Views: 624

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198083

There's an extra <Thing> that's confusing the compiler. Change

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

to

public class Bag implements Container<Thing> {

Right now you're creating a new type variable named Thing that hides the existing Thing interface. What you're writing now is equivalent to

public class Bag<E> implements Container<E> 

...just with a variable named Thing instead of E.

Upvotes: 8

Related Questions