Not sure of a good way to word this: If I have a generic SuperClass<T>
and a subclass that explicitly parameterizes the superclass (i.e. SubClass extends SuperClass<SubParameter>
, why can't the subclass be used to instantiate an instance of the superclass that's parameterized with a superclass of the parameter the subclass uses (i.e. SuperClass<SuperParameter> = SubClass<SubParameter>
).
Example
Since that was a mess of sub/super class, here's an example:
I have a generic class Block
parameterized by types that extend class Shape
. I then make a subclass SquareBlock extends Block
that explicitly specifies the type parameter of its superclass. That type parameter is a subclass of the expected type parameter in the superclass (Square extends Shape
).
Question: Why can't an instance of SquareBlock
be used in a variable of type Block<Shape>
, since both SquareBlock extends Block
and Square extends Shape
are true?
// outer class
class Block <T extends Shape> {}
class SquareBlock extends Block<Square> {}
// inner class used in type of outer class
class Shape {}
class Square extends Shape {}
public class Generics {
public static void main(String[] args) {
// Square class can be used where Shape class is specified
Shape shape = new Square(); // works
List<Shape> list = new ArrayList<>();
list.add(new Square()); // works
Block<Shape> block = new SquareBlock();
// Type mismatch: cannot convert from SquareBlock to Block<Shape>
}
}