java 构造函数可以将接口作为参数吗

Can a java constructor have interfaces as arguments

我正在试验Java接口,下面的代码报错了。

在class中,构造函数将Map作为参数

public class ClassA{
  private Map<String,InterfaceA> testMap;
  ClassA(Map<String,InterfaceA> testMap){
    this.testMap=testMap;
  }
}



public class ClassB{
  ClassA testA = new ClassA(new HashMap<String,ImplmntsInterfaceA>); //1st declaration
  Map<String,ImplmntsInterfaceA> testMap=new HashMap<String,ImplmntsInterfaceA>(); //Second declaration
  ClassA testB = new ClassA(testMap);
}

ImplmntsInterfaceA 是实现 InterfaceA.

的 class

两个 ClassA 声明都给出了错误,首先建议将 Map 构造函数更改为 HashMap,然后要求将 InterfaceA 通用替换为 ImplmntsInterfaceA

有人可以帮忙解决为什么它不起作用吗?

谢谢:)

我怀疑您想在 ClassA 构造函数签名(和字段)中将 Map<String,InterfaceA> 更改为 Map<String, ? extends InterfaceA>。否则 HashMap<String, ImplmntsInterfaceA> 确实不是它的有效参数。

考虑哪些操作在 Map<String,InterfaceA> 上有效 - 你可以这样写:

map.put("foo", new SomeArbitraryImplementationOfA());

这对 Map<String, ImplmntsInterfaceA> 无效,因为后者的值必须是 ImplmntsInterfaceA。编译器正在保护您免受这种情况的影响。

如果您使用 Map<String, ? extends InterfaceA>,您将无法在 ClassA 内进行任何 write 操作(因为您不知道什么值是有效的),但您将能够从地图中 获取 ,知道每个值至少实现 InterfaceA.

这基本上是为什么 List<Banana> 不是 List<Fruit>...

的更复杂版本

请查看您的 ClassA 构造函数。

ClassA(Map<String,InterfaceA> testMap){ // *
  this.testMap=testMap;
}

现在您的构造函数(*) 将接受Map<String, InterfaceA> 类型或Map<String,InterfaceA> 实现。例如:HashMap<String, InterfaceA>.

您可以将构造函数更改为以下以接受 HashMap<String,ImplmntsInterfaceA>

例如:

ClassA(Map<String,? extends InterfaceA> testMap){ 
  this.testMap=testMap;
}