4

Is it necessary to parametrize the entire interface for this scenario, even though Bar is only being used in a single 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....

}

3 Answers 3

5

No, it's not necessary from a syntactic standpoint. You can also do this:

public interface IFoo {

  <T> void method1(Bar<T> bar);

  /* Many other methods that don't use Bar…  */

}

Or this:

public interface IFoo {

  void method1(Bar<?> bar);

  /* Many other methods that don't use Bar…  */

}

The correct choice depends on the semantics of IFoo and what its implementations are likely to do with the Bar instances they receive through method1.

Sign up to request clarification or add additional context in comments.

Comments

2

I would ask the question a bit differently, because the need suggests a cost, which is not actual. I don't think it actually matter if it is used on only one, or several methods.

When you make several calls to the instance, how does the type parameter vary?:

  • if constant once you instantiated the instance, you parameterize the entire interface.
  • if it may be different on each call, you parameterize the method.

That way, the type of parameter actually gives information about the code, improve the meaning and clarity.


Edited: Example

If sometimes, the type parameter varies from call to call, for the same instance ...
It has to be a method parameter.

2 Comments

It is likely that some implementation of IFoo will keep the parameter type constant, while other implementation it may vary :)
I don't think there would be any way for some implementations to enforce a particular type parameter while others allow it to change.
0

You're not extending the interface. Is that deliberate? You can do this:

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

Just doing this:

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

won't compile.

2 Comments

sorry, should've been implementing.
I'm glad you pointed that out. It improved the question a lot, so I believe more people will try to answer it now :-)

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.