Scala Programming Projects
上QQ阅读APP看书,第一时间看更新

Subclass assignment

Consider two classes, A and B, with B extends A.

When you declare a variable of type A, you can assign it to an instance of B, with val a: A = new B.

On the other hand, if you declare a variable of type B, you cannot assign it to an instance of A.

Here is an example that uses the same Shape and Rectangle definitions that were described earlier:

val shape: Shape = new Rectangle(x = 0, y = 3, width = 3, height = 2)
val rectangle: Rectangle = new Shape(x = 0, y = 3)

The first line compiles because Rectangle is a Shape.

The second line does not compile, because not all shapes are rectangles.