0

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?

4
  • 3
    Should probably be implements Foo<Bippie>. Follow your IDE's guidance. Commented Jun 3, 2014 at 19:31
  • 1
    makes it parametrized that's what it's designed by you. If you don't want to use generic they why are you making the interface generic. First read why use generic? What is benefit of using Generic? Commented Jun 3, 2014 at 19:31
  • 1
    It might help you to understand it directly from the official Oracle document on Generic Type. Commented Jun 3, 2014 at 19:38
  • Generics add stability to your code by making more of your bugs detectable at compile time. Commented Jun 3, 2014 at 19:38

1 Answer 1

3

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() {
Sign up to request clarification or add additional context in comments.

7 Comments

in the first part of your answer: public class Baz implements Foo<Bippie> {, will Baz#get() return the Bippie type only? Or will Bar be an acceptable return type since public interface Foo<S extends Bar> { Optional<S> get() ... }?
It would have to be an Optional<Bippie>, because Baz is defining the S from Foo to be Bippie.
Ah, so when implementing the Foo interface, Foo's type parameter must be a sub-type of Bar?
It could be a subtype of Bar or it could be Bar itself.
I'm confused: (The use of the keyword extends is slightly misleading: recall from Item 26 that subtype is defined so that every type is a subtype of itself, even though it does not extend itself.) -Effective Java (page 134 in my Kindle)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.