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

Abstract class

An abstract class is a class that can have many abstract members. An abstract member defines only a signature for an attribute or a method, without providing any implementation. You cannot instantiate an abstract class: you must create a subclass that implements all the abstract members.

Replace the definition of Shape and Rectangle in the worksheet as follows:

abstract class Shape(val x: Int, val y: Int) {
val area: Double
def description: String
}

class Rectangle(x: Int, y: Int, val width: Int, val height: Int)
extends Shape(x, y) {

val area: Double = width * height

def description: String =
"Rectangle " + width + " * " + height
}

Our class Shape is now abstract. We cannot instantiate a Shape class directly anymore: we have to create an instance of Rectangle or any of the other subclasses of Shape. Shape defines two concrete members, x and y, and two abstract members, area and description. The subclass, Rectangle, implements the two abstract members.

You can use the prefix override when implementing an abstract member, but it is not necessary. I recommend not adding it to keep the code less cluttered. Also, if you subsequently implement the abstract method in the superclass, the compiler will help you find all subclasses that had an implementation. It will not do this if they use override
主站蜘蛛池模板: 康马县| 阿拉善右旗| 曲周县| 中牟县| 同仁县| 凤冈县| 石柱| 普定县| 泗阳县| 延安市| 青浦区| 洛阳市| 南阳市| 沈丘县| 巧家县| 静乐县| 固始县| 万年县| 天长市| 霍邱县| 阿鲁科尔沁旗| 灌云县| 阿合奇县| 惠来县| 巴彦淖尔市| 阜南县| 茂名市| 武平县| 洪湖市| 襄垣县| 湖南省| 滁州市| 巴楚县| 封丘县| 台东市| 嵊泗县| 广安市| 攀枝花市| 黄石市| 察雅县| 安新县|