Java generics - method parameter

Do I need to parameterize the entire interface for this scenario, although Bar is used in only one method?

public interface IFoo<T>{ void method1(Bar<T> bar); //Many other methods that don't use Bar.... } public class Foo1 implements IFoo<Yellow>{ void method1(Bar<Yellow> bar){...}; //Many other methods that don't use Bar.... } public class Foo2 implements IFoo<Green>{ void method1(Bar<Green> bar){...}; //Many other methods that don't use Bar.... } 
+4
source share
3 answers

No, this is not necessary from a syntactical point of view. You can also do this:

 public interface IFoo { <T> void method1(Bar<T> bar); /* Many other methods that don't use Bar… */ } 

Or that:

 public interface IFoo { void method1(Bar<?> bar); /* Many other methods that don't use Bar… */ } 

The right choice depends on the semantics of IFoo and what its implementations can do with the Bar instances that they receive through method1 .

+5
source

I would ask the question a little differently, because need offers a cost that is not relevant. I do not think that it is really important if it is used only for one or several methods.

When you make multiple calls to an instance , how does a parameter of type <change :

  • If the constant is after the instance instance, you parameterize the entire interface.
  • if it may be different for each call, you parameterize the method.

Thus, the type of the parameter actually gives information about the code, improves the meaning and clarity.


Edited : Example

If sometimes the type parameter changes from call to call, for the same instance ...
It must be a parameter of the method.

+2
source

You are not expanding the interface. Is this intentional? You can do it:

 public class Foo2 implements IFoo<Green> { void method1(Bar<Green> bar); } 

Just do this:

 public class Foo<Green> { void method1(Bar<Green> bar); } 

will not compile.

0
source

All Articles