还有另一种Java泛型“不兼容类型".编译错误 [英] Yet another Java generics "incompatible types" compilation error

查看:52
本文介绍了还有另一种Java泛型“不兼容类型".编译错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些代码,并遇到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>中的TValue<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 ,并且类型ObjectT不同.

您必须使用

private Constant(Constant<T> instance)

代替

private Constant(Constant instance)

因为这与private Constant(Constant<Object> instance)

这篇关于还有另一种Java泛型“不兼容类型".编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆