- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
A Tour of Scala: Subclassing
Created by admin on 2008-07-05.
Updated: 2008-12-21, 01:17
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 superclassPoint
; in our case, we inherit the valuesx
,y
, as well as methodmove
. - Subclass
ColorPoint
adds a new methodcompareWith
to the set of (inherited) methods. - Scala allows member definitions to be overridden; in our case we override the
move
method from classPoint
. This makes themove
method of classPoint
inaccessible to clients ofColorPoint
objects. Within classColorPoint
, the inherited methodmove
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 methodmove
return aColorPoint
object instead of aPoint
object as specified in superclassPoint
. - Subclasses define subtypes; this means in our case that we can use
ColorPoint
objects wheneverPoint
objects 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.