- 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.
- 面向物聯(lián)網(wǎng)的CC2530與傳感器應用開發(fā)
- HTML5 Game development with ImpactJS
- PLC、現(xiàn)場總線及工業(yè)網(wǎng)絡實用技術(shù)速成
- 2018網(wǎng)信發(fā)展報告
- 物聯(lián)網(wǎng)通信技術(shù)
- 物聯(lián)網(wǎng)工程概論
- 網(wǎng)絡工程實施技術(shù)與方案大全
- 一本書讀懂物聯(lián)網(wǎng)
- 數(shù)據(jù)血緣分析原理與實踐
- 物聯(lián)網(wǎng)的機遇與利用
- 深入理解計算機網(wǎng)絡
- 物聯(lián)網(wǎng)與智慧農(nóng)業(yè)
- 新媒體交互藝術(shù)
- 想象的互動:網(wǎng)絡人際傳播中的印象形成
- 物聯(lián)網(wǎng)傳感器技術(shù)與應用