Classes in Scala are extensible. A subclass mechanism makes it possible to specialize a class by inheriting all members of a given superclass and defining additional class members.
Here is an example:
class Point(xc: Int, yc: Int) { val x: Int = xc val y: Int = yc def move(dx: Int, dy: Int): Point = new Point(x + dx, y + dy) } class ColorPoint(u: Int, v: Int, c: String) extends Point(u, v) { val color: String = c def compareWith(pt: ColorPoint): Boolean = (pt.x == x) && (pt.y == y) && (pt.color == color) override def move(dx: Int, dy: Int): ColorPoint = new ColorPoint(x + dy, y + dy, color) }
In this example we first define a new class Point for representing points. Then we define a class ColorPoint which extends class Point.
This has several consequences:
ColorPoint inherits all members from its superclass Point; in our case, we inherit the values x, y, as well as method move.ColorPoint adds a new method compareWith to the set of (inherited) methods.move method from class Point. This makes the move method of class Point inaccessible to clients of ColorPoint objects. Within classColorPoint, the inherited method move can be accessed with a super call: super.move(...). Opposed to Java where method overriding is invariant (i.e. the overriding method has to have the same signature), Scala allows methods to be overridden in a contra/covariant fashion. In the example above we make use of this feature by letting method move return a ColorPoint object instead of a Point object as specified in superclass Point.ColorPoint objects whenever Pointobjects are required.For cases where we would like to inherit from several other classes, we have to make use of mixin-based class composition [1] as opposed to pure subclassing.
Links:
[1] http://www.scala-lang.org/node/117