2

I'm trying to write a Queue class using a pre-written interface. The interface contains the method

public void enqueue(T element);

and my class looks like

import java.util.ArrayList;

public class Queue<T> implements QueueInterface {

    ArrayList<T> list = new ArrayList<>();

    public void enqueue(T element){
        list.add(element);
    }
}

Currently, this results in the class generating an error saying it needs to implement the enqueue method, the override statement generates an error saying that the method doesn't override the one in my interface, and the method declaration in my class, without the override, says that it clashes with the interface's method.

rgettman
  • 167,281
  • 27
  • 248
  • 326

2 Answers2

2

Here is explanation on the error:

From the code your provided, there is 2 error and 1 warning.
Warning 1:

QueueInterface is a raw type. References to generic type QueueInterface should be parameterized

Error 1:

The type Queue must implement the inherited abstract method QueueInterface.enqueue(Object)

Error 2:

Name clash: The method enqueue(T) of type Queue has the same erasure as enqueue(Object) of type QueueInterface but does not override it

Warning 1 tells that you should specify the generic type of QueueInterface. Without specifying the type parameter, compiler will assume you are implementing something like QueueInterface<Object>(not exactly see the reference 1). Hence you see Error 1 as there is no method implement/override enqueue(Object) in Queue.

Then why can't enqueue(T) override enqueue(Object)? When adding @Override annotation to enqueue(T element) method, another error will show:

The method enqueue(T) of type Queue must override or implement a supertype method

This is because enqueue(T) is generic method and T can be any type. For example, if we declare

Queue<String> stringQueue = new Queue<String>();
Queue<Integer> integerQueue = new Queue<Integer>();

Then enqueue method of stringQueue and integerQueue accept String and Integer respectively, both cannot accept Object as argument, and hence cannot override enqueue(Object).

And finally for Error 2, it is quite confusing as it says that enqueue(T) collides with enqueue(Object), but enqueue(T) does not override enqueue(Object). These two method collide because of erasure. Which means that in Runtime, all T is replaced by Object. Program will not know which method to execute in this case. See reference 2 for details.

Reference:

1.What is a raw type and why shouldn't we use it?(Excellent Question and Answer on Raw Type and related stuff)

2.Java generics type erasure: when and what happens?

samabcde
  • 3,622
  • 1
  • 18
  • 28
1

Define your Queue class like below with QueuInterface implementation.

    public class Queue<T> implements QueueInterface<T> {

        @Override
        public void enqueue(T element) {

        }

    } 
Pandey Amit
  • 557
  • 5
  • 17