是否有必要为此方案参数化整个界面,即使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....
}
答案 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);
}
不会编译。