May*_*mar 1 java constructor interface
我正在尝试Java接口,以下代码给出了错误.
在类中,构造函数将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);
}
Run Code Online (Sandbox Code Playgroud)
ImplmntsInterfaceA是一个实现的类InterfaceA.
这两个ClassA声明都给出了错误,首先建议将Map构造函数更改为,HashMap然后再次要求将InterfaceA泛型替换为ImplmntsInterfaceA.
有人可以帮忙解决它为什么不起作用?
谢谢 :)
我怀疑你想要改变Map<String,InterfaceA>到Map<String, ? extends InterfaceA>的ClassA构造函数签名(及场).否则,HashMap<String, ImplmntsInterfaceA>真的不是它的有效论据.
考虑哪些操作有效Map<String,InterfaceA>- 你可以写:
map.put("foo", new SomeArbitraryImplementationOfA());
Run Code Online (Sandbox Code Playgroud)
这对于a无效,Map<String, ImplmntsInterfaceA>因为后者的值必须是a ImplmntsInterfaceA.编译器正在保护您.
如果您使用Map<String, ? extends InterfaceA>,您将无法在其中进行任何写入操作ClassA(因为您不知道哪些值有效),但您将能够从地图中获取,因为知道每个值至少实现InterfaceA.
这基本上是一个更复杂的版本,为什么一个List<Banana>不是List<Fruit>...
| 归档时间: |
|
| 查看次数: |
125 次 |
| 最近记录: |