[英]Why do classes that implement an interface not count as the same type as the interface in Java?
I have 我有
out.load(output, transactions, columnHeaders, dataFormat);
Where load
is defined as: 其中load
定义为:
public boolean load(String outputfile, List<Transaction> transactions, List<String> columnHeaders, String dataFormat);
and 和
String output = "";
String dataFormat = "";
ArrayList<ARTransaction> transactions = new ArrayList<ARTransaction>();
List<String> columnHeaders = null;
where 哪里
ARTransaction implements Transaction
Why is there a problem on the type of transactions
? 为什么transactions
类型有问题?
public boolean load(String outputfile, List<? extends Transaction> transactions, List<String> columnHeaders, String dataFormat);
Or just declare transactions as a List<Transaction>
. 或者只是将事务声明为List<Transaction>
。
Here's the common example of why you obviously can't do this: 以下是为什么你显然不能这样做的常见例子:
List<String> list = new ArrayList<String>();
List<Object> objList = list; //if this were possible
objList.add(Integer.valueOf(5));
String val = list.get(0); //ClassCastException here
System.out.println(val);
It is having difficulties casting the contravariant type that is from ArrayList<ARTransaction>
to List<Transaction>
. 将ArrayList<ARTransaction>
的逆变类型ArrayList<ARTransaction>
为List<Transaction>
遇到困难。
Try List<? extends Transaction>
试用List<? extends Transaction>
List<? extends Transaction>
instead List<? extends Transaction>
因为它可能不满足Liskov替代原则 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.