This page is no longer maintained — Please continue to the home page at www.scala-lang.org

A Tour of Scala: Subclassing

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:

  • Class ColorPoint inherits all members from its superclass Point; in our case, we inherit the values xy, as well as method move.
  • Subclass ColorPoint adds a new method compareWith to the set of (inherited) methods.
  • Scala allows member definitions to be overridden; in our case we override the 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.
  • Subclasses define subtypes; this means in our case that we can use 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 as opposed to pure subclassing.

 

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland