I am trying to achieve assigning a class that implements a generic typed interface. It's doable in C# with out keyword per 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>();
But when I tried to achieved the same in Java, it failed:
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
}
}
The error is -> Type mismatch: cannot convert from Rectangle to IShape from Java 8's compiler. How can I achieve assigning a class that implements IShape to a reference of interface IShape< T>?