1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| package com.scala.first
/** * Created by common on 17-4-16. */ object AbstractClass {
def main(args: Array[String]): Unit = { val ae = new ArrayElement(Array("hello", "world")) println(ae.width)
val list1 = List(1,2,3,4) val list2 = List(1,2,3,4,5) //Scala中同时遍历两个list,如果长度不一样会截去 for((line1,line2) <- list1 zip list2){ println(line1+line2) } }
}
//定义一个抽象类 abstract class Element {
//定义无参方法,抽象成员 def contents: Array[String]
def height: Int = contents.length
def width: Int = if (height == 0) 0 else contents(0).length
}
//扩展类,继承了上面的抽象类,需要实现抽象类中的方法 class ArrayElement(content: Array[String]) extends Element { def contents: Array[String] = content }
//更加简洁的写法,contents和Element中的contents保持一致 class ArrayElement2(val contents: Array[String]) extends Element
//另一个例子 class cat { //确保一个成员不被子类重写,需要把其定义成final // final val dangerous = false val dangerous = false }
class tiger(override val dangerous: Boolean, private var age: Int) extends cat
|