Java泛型 - 方法参数

时间:2009-10-20 15:22:11

标签: java generics

是否有必要为此方案参数化整个界面,即使Bar仅在单个方法中使用?

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 个答案:

答案 0 :(得分:5)

不,从句法角度来看,没有必要。你也可以这样做:

public interface IFoo {

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

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

}

或者这个:

public interface IFoo {

  void method1(Bar<?> bar);

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

}

正确的选择取决于IFoo的语义及其实现可能与他们通过Bar收到的method1实例的相关性。

答案 1 :(得分:2)

我会问这个问题有点不同,因为need表示费用,这不是实际的。如果它仅用于一种或多种方法,我认为它实际上并不重要。

当您对该实例进行多次调用时,该类型参数的变化情况如何?

  • 如果在实例化实例后保持不变,则可以参数化整个界面。
  • 如果在每次通话时可能不同,则可以参数化该方法。

这样,参数类型实际上提供了有关代码的信息,提高了意义和清晰度。


已修改:示例

如果有时候,类型参数因呼叫而异,对于同一个实例...
必须是方法参数

答案 2 :(得分:0)

您没有扩展界面。这是故意的吗?你可以这样做:

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

这样做:

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

不会编译。