还有另一种Java泛型和“不兼容类型".编译错误 [英] Yet another Java generics "incompatible types" compilation error
问题描述
我正在编写一些代码,并遇到incompatible types
编译错误.
这就是我所拥有的:
I was writing some code and came across a incompatible types
compilation error.
This is what I have:
public interface Expression<T> {
int getArity();
T evaluate();
}
public abstract class Value<T> implements Expression<T> {
@Override
public final int getArity() { return 0; }
}
public final class Constant<T> extends Value<T> {
private final T value;
/** Parameter constructor of objects of class Constant. */
public Constant(T val) {
value = val;
}
/** Copy constructor of objects of class Constant. */
private Constant(Constant instance) {
value = instance.evaluate(); // Error here.
}
@Override
public T evaluate() { return value; }
}
I thought I wasn't declaring generics correctly when using inheritance, so I checked Oracle's tutorial, in which they write
interface PayloadList<E,P> extends List<E>
上面的声明使用相同的通用类型E
,这是我在示例中想要完成的.似乎假设Constant<T>
中的T
与Value<T>
中的不同.否则,它应该能够合并两个T
并看到它是相同的类型.
如何正确实现我要实现的目标?
The above declaration uses the same generic type E
, which is what I want to accomplish in my example. It seems to be assuming that the T
from Constant<T>
is different from the one from Value<T>
. Otherwise it should be able to merge both T
and see it's the same type.
How can I correctly implement what I'm trying to achieve?
(即,事物的常量是事物的值,这是相同事物的表达)
推荐答案
您的instance
变量定义为Constant instance;
如果您没有在变量上指定泛型,则泛型类型将自动为Object
,并且类型Object
与T
不同.
您必须使用
private Constant(Constant<T> instance)
代替
private Constant(Constant instance)
因为这与private Constant(Constant<Object> instance)
这篇关于还有另一种Java泛型和“不兼容类型".编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!