Kevin Meredith
Kevin Meredith

Reputation: 41909

Implementing a Parameterized Interface

Given this interface:

import com.google.common.base.Optional;

public interface Foo<S extends Bar> {
  Optional<S> get();    
}

Then I've implemented the interface with Foo:

public class Baz implements Foo {
   public Optional<Bippie> get { ... }; // Bippie extends Bar
{

Is it necessary to put parameters on class Baz? Why or why not?

Upvotes: 0

Views: 2210

Answers (1)

rgettman
rgettman

Reputation: 178263

It is technically legal to leave Baz as it is, implementing the raw Foo interface. Java will treat all generics as if they don't exist, and that code will compile.

It's generally a bad idea to use raw types, however, and it's easy to implement the generic interface properly, so just do that. You don't have to provide a generic type parameter on the class Baz:

public class Baz implements Foo<Bippie> {
    public Optional<Bippie> get() {

But you can if you want to:

public class Baz<S extends Bar> implements Foo<S> {
    public Optional<S> get() {

Or you could use Bippie to narrow it further:

public class Baz<S extends Bippie> implements Foo<S> {
    public Optional<S> get() {

Upvotes: 3

Related Questions