Scala繼承一個基類跟Java很類似, 但咱們須要注意如下幾點:ide
1 class Point(val xc: Int, val yc: Int){ 2 var x: Int = xc 3 var y: Int = yc 4 def move(dx: Int, dy: Int): Unit ={ 5 x = x + dx 6 y = y + dy 7 println("x點的座標是:" + x) 8 println("y點的座標是:" + y) 9 } 10 11 var name = "" 12 override def toString = getClass.getName + "[name=" + name + "]" 13 }
1 class Location(override val xc: Int, override val yc: Int, 2 val zc: Int) extends Point(xc, yc){ // 繼承 重寫了父類的字段 3 var z: Int = zc 4 def move(dx: Int, dy: Int, dz: Int){ 5 x = x + dx 6 y = y + dy 7 z = z + dz 8 println("x點的座標是:" + x) 9 println("y點的座標是:" + y) 10 println("z點的座標是:" + z) 11 } 12 13 var salary = 0.0 14 override def toString = super.toString + "[salary=" + salary + "]" 15 }
1 object Test{ 2 def main(args: Array[String]): Unit = { 3 val loc = new Location(10, 20, 30) 4 loc.move(10, 10 ,5)、 6 loc.name = "lc" 7 loc.salary = 35000.0 8 println(loc) 9 } 10 }