- 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.
- 網絡云百問百答
- HTML5 Game development with ImpactJS
- 無人機通信
- 射頻通信系統
- Getting Started with Grunt:The JavaScript Task Runner
- 智慧光網絡:關鍵技術、應用實踐和未來演進
- SAE原理與網絡規劃
- 智能物聯網:區塊鏈與霧計算融合應用詳解
- Microservices Development Cookbook
- 網絡分析技術揭秘:原理、實踐與WinPcap深入解析
- 從實踐中學習Kali Linux網絡掃描
- XSS跨站腳本攻擊剖析與防御
- Learn Node.js by Building 6 Projects.
- Next.js Quick Start Guide
- 企業自動駕駛網絡架構與技術