我有三门课:
public abstract class fileHandler<Key extends Object, Value extends Object> {
}
public A extends fileHandler<String, String[]> {
}
public B extends fileHandler<String, String> {
}
现在在我的主要函数中我做了这样的事情:
fileHandler file= null;
If (<condition>) {
fileHandler = new A();
} else
fileHandler = new B():
}
但这会产生 2 个编译时错误:
- 无法将 A 转换为 fileHandler
- 无法将 B 转换为 fileHandler
如何消除这些错误,因为如果基类不是通用的,我就不会收到此错误。
更新:
我的类层次结构是:
-
class fileHandler<Key, Value> { }
-
class A extends fileHandler<String, String[]> { }
-
class B extends fileHandler<String, String> { }
- 调用函数
gen(object of A)
的 C 类或 - 调用函数
gen(object of B)
的 D 类。 - C 和 D 均派生自抽象类 E。
现在我应该如何在 C、D 和 E 中定义这些函数:
我给出了以下内容:
E:
public abstract void gen (fileHandler A) throws exception;
C:
void gen (fileHandler A) throws exception;
D:
void gen (fileHandler A) throws exception;
C、D 和 E 给出错误 fileHandler 是原始类型。对泛型类型 fileHandler(Key, Value) 的引用应该参数化。
最佳答案
当您使用不同类型参数实例化泛型类型时,这两个实例化不类型兼容。泛型类型的不同实例化并不像从另一个类继承的类与该类类型等效那样类型等效,即使类型参数本身可能通过继承相关。通用性和多态性是两个独立的语言特性。
您的代码相当于以下内容:
// Java defaults unspecified type arguments to Object.
fileHandler<Object, Object> file;
if (...) {
// Error: fileHandler<String, String> is not equivalent to fileHandler<Object, Object>
file = new fileHandler<String, String>();
} else {
// Error: fileHandler<String, String[]> is not equivalent to fileHandler<Object, Object>
file = new fileHandler<String, String[]>();
}
如果您确实想隔离一个独立于用于实例化 fileHandler 类的类型的多态接口(interface),那么我建议您使用一个接口(interface):
interface IFileHandler
{
// If this interface needs to talk about keys and values, it
// does so using only java.lang.Object.
}
public class fileHandler<Key extends Object, Value extends Object>
implements IFileHandler
{
// ...
}
public class A extends fileHandler<String, String>
{
// ...
}
public class B extends fileHandler<String, String[]>
{
// ...
}
IFileHandler file;
if (...) {
file = new A();
} else {
file = new B();
}
关于java - 泛型和继承问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5439209/