简体   繁体   English

为什么实现接口的类不算与Java中的接口类型相同?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM