Another Java generic “incompatible type” compilation error

I was writing some code and encountered incompatible type compilation errors

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 don't think I declared generics correctly when using inheritance, so I checked Oracle's tutorial and they wrote

interface PayloadList<E,P> extends List<E>

The above declaration uses the same generic type E, which I want to do in my example It seems to assume that t comes from constant < T > Different from that in value < T > Otherwise, it should be able to merge two t's and see that they are of the same type How can I correctly achieve the goal I want to achieve?

(that is, the constant of something is the value of something, which is the expression of the same thing)

Solution

Your instance variable is defined as a constant instance;

If no generic type is specified on the variable, the generic type will be automatically object, and the object type is different from t

You must use

private Constant(Constant<T> instance)

replace

private Constant(Constant instance)

Because this is the same as private constant (constant < Object > instance)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>