- Scala Programming Projects
- Mikael Valot Nicolas Jorand
- 384字
- 2021-07-23 16:25:14
Overriding methods
When you derive a class, you can override the members of the superclass to provide a different implementation. Here is an example that you can retype in a new worksheet:
class Shape(val x: Int, val y: Int) {
def description: String = s"Shape at (" + x + "," + y + ")"
}
class Rectangle(x: Int, y: Int, val width: Int, val height: Int)
extends Shape(x, y) {
override def description: String = {
super.description + s" - Rectangle " + width + " * " + height
}
}
val rect = new Rectangle(x = 0, y = 3, width = 3, height = 2)
rect.description
When you run the worksheet, it evaluates and prints the following description on the right-hand side:
res0: String = Shape at (0,3) - Rectangle 3 * 2
We defined a method description on the class Shape that returns a String. When we call rect.description, the method called is the one defined in the class Rectangle, because Rectangle overrides the method description with a different implementation.
The implementation of description in the class Rectangle refers to super.description. super is a keyword that lets you use the members of the superclass without taking into account any overriding. In our case, this was necessary so that we could use the super reference, otherwise, description would have called itself in an infinite loop!
On the other hand, the keyword this allows you to call the members of the same class. Change Rectangle to add the following methods:
class Rectangle(x: Int, y: Int, val width: Int, val height: Int)
extends Shape(x, y) {
override def description: String = {
super.description + s" - Rectangle " + width + " * " + height
}
def descThis: String = this.description
def descSuper: String = super.description
}
val rect = new Rectangle(x = 0, y = 3, width = 3, height = 2)
rect.description
rect.descThis
rect.descSuper
When you evaluate the worksheet, it prints the following strings:
res0: String = Shape at (0,3) - Rectangle 3 * 2
res1: String = Shape at (0,3) - Rectangle 3 * 2
res2: String = Shape at (0,3)
The call to this.description used the definition of description, as declared in the class Rectangle, whereas the call to super.description used the definition of description, as declared in the class Shape.