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

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
主站蜘蛛池模板: 辉南县| 铁岭市| 宣威市| 伊川县| 自治县| 阿巴嘎旗| 甘南县| 乌拉特前旗| 东安县| 田林县| 资兴市| 泗水县| 桐乡市| 永定县| 丰原市| 德钦县| 那坡县| 和平区| 通榆县| 红原县| 集贤县| 来凤县| 通化县| 三亚市| 林口县| 个旧市| 陵川县| 商城县| 百色市| 静海县| 百色市| 新民市| 松江区| 崇礼县| 新疆| 广昌县| 铜梁县| 阿图什市| 理塘县| 小金县| 南阳市|