Java将实现的类分配给通用接口

时间:2015-03-09 19:06:32

标签: java generics interface

我正在尝试分配一个实现泛型类型接口的类。它可以在C#中使用https://msdn.microsoft.com/en-us/library/dd997386.aspx的关键字:

interface ICovariant<out R>
{
    R GetSomething();
}
class SampleImplementation<R> : ICovariant<R>
{
    public R GetSomething()
    {
        // Some code. 
        return default(R);
    }
}

// The interface is covariant.
ICovariant<Button> ibutton = new SampleImplementation<Button>();
ICovariant<Object> iobj = ibutton;

// The class is invariant.
SampleImplementation<Button> button = new SampleImplementation<Button>();

但是当我尝试在Java中实现相同的功能时,它失败了:

interface IShape<T>
{
    T GetArea();
}

class Rectangle implements IShape<Number>
{
    public Number GetArea() {
        Double d = new Double(1.03);
        return d;
    }
}

class Test {
    void Try() {
        Rectangle r = new Rectangle();
        IShape<Object> s0 = r;//assignment failed
    }
}

错误是 - &gt;类型不匹配:无法从Java 8的编译器将Rectangle转换为IShape。如何实现将实现IShape的类分配给接口IShape的引用&lt; T&GT;

1 个答案:

答案 0 :(得分:0)

尝试替换此行:

class Rectangle implements IShape<Number>

有了这个:

class Rectangle<T extends Number> implements IShape<T>