2 ms·
Indeed. When you read from a Rectangle, you want it to behave like a Rectangle or a more specific subclass. When you write to a Rectangle, you want it to behave
by nayuki 6y ago
Indeed. When you read from a Rectangle, you want it to behave like a Rectangle or a more specific subclass. When you write to a Rectangle, you want it to behave like a Rectangle or a more general superclass.
This is related to the PECS principle in generics:
class List<E> {
appendToMyself(List<? extends E> producer);
copyMyselfTo(List<? super E> consumer);
}
- ttymck 6y agoAre you referring to "contravariance/covariance"? If so , is that the same as if I suggested that calling the Rectangle method `setWidth` on a Square should return a Rectangle (that is _possibly_ a Square)? i.e. val mySquare: Square = new Square(20) val myMutatedSquare: Rectangle = mySquare.setWidth(40) // 20 x 40