官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 昔阳县| 新营市| 和龙市| 双鸭山市| 志丹县| 磐安县| 南溪县| 定西市| 磐石市| 罗源县| 岢岚县| 额敏县| 乌兰浩特市| 贞丰县| 连山| 延寿县| 德化县| 霍州市| 游戏| 江川县| 雷波县| 江永县| 睢宁县| 芮城县| 青海省| 杭锦后旗| 柳林县| 金沙县| 招远市| 沙田区| 红桥区| 内黄县| 凉城县| 云龙县| 庆安县| 柳州市| 香港| 阜康市| 莱芜市| 开平市| 吉安县|