วันจันทร์ที่ 4 พฤษภาคม พ.ศ. 2558

Inheritance

เราสามารถ inherit class ได้ใน ภาษา Scala  เหมือนกันกับ ภาษาต่างๆ เช่น java หรือ c# ตัวอย่างเช่น

เรามี class Point ที่ประกาศ x และ y เป็น int   และมีเมทธอด print ที่พิมพ์ค่า x และ y ออกมา

class Point(x: Int, y : Int) {
   def print() = {
     println(s"${this.x}, ${this.y}")
   }
}

เราสามารถ extends class นี้มาใช้เช่น

class ColorPoint(x: Int, y :Int) extends Point(x,y) {
  var color : String = _
  
  this.init()
  
  def init() {
    if (this.x == 0
       this.color = "red"
    else
       this.color = "green"
  }
  
  override def print() = {
     println(s"${this.x}, ${this.y} --> ${this.color}")
  }
}

สังเตุได้ว่าเราเรียก  base constructor  ด้วย  Point(x,y)  และเพิ่ม data member  อีกหนึ่งตัวคือ color นอกจากนี้ เรายัง override เมทธอด print เพื่อพิมพ์ค่าของ color ออกมาอีกด้วย ลองมาดูวิธีเรียกใช้กัน 

object Hello {
  def main(args: Array[String]) {
    val p1 =new ColorPoint(1,2)
    p1.print()
  }
}

เราสร้าง object แบบ ColorPoint แล้วพิมพ์ค่าออกมา จะได้

1, 2 --> green

ทีนี้มาดูอีกตัวอย่างหนึ่ง ในตัวอย่างข้างล่างนี้ compile ไม่ผ่านนะครับ ในภาษา Scala ไม่มีให้เรียก super ซึ่งเป็นที่น่ารำคาญสำหรับคนที่เขียน java/c# มาก่อน

class Point {
   var x :Int = _
   var y :Int = _
  
   def this(x:Int, y:Int) {
     this()
     this.x = x
     this.y = y
   }
   
   def print() = {
     println(s"${this.x}, ${this.y}")
   }
}

class ColorPoint extends Point {
  var color : String = _

  def this(x:Int, y:Int) {
    super(x,y)  // compile error here; this expected but 'super' found
    if (this.x == 0
       this.color = "red"
    else
       this.color = "green"
  }
  override def print() = {
     println(s"${this.x}, ${this.y} --> ${this.color}")
  }

หมายเหตุ เราเรียก constructor ของ class Point ที่อยู่ในบรรทัดข้างล่างนี้ว่า  Primary Constructor

class Point(x: Int, y : Int)

อย่างไรก้อตามถ้า base class มี constructor อยู่หลายตัวเราสามารถเลือกได้ว่าจะเรียกใช้ตัวไหนเช่น

class Point(var x:Int, var y:Int) {
   def this(x: Int) {
     this(x,0) //always call primary constructor
   }   
   def this() {
     this(0) //call above constructor then primary constructor
   } 
}

class ColorPoint extends Point { }
class MutliPoint extends Point(10) { }

class AnotherPoint extends Point(10,20) { }

จะเห็นว่า ColorPoint เลือกที่จะเรียก constructor ของ Point ที่ไม่มี parameter อะไรเลย  MultiPoint เลือก constructor ที่รับ x:Int   ส่วน AnotherPoint เลือก constructor ทีรับทั้ง x และ y 

ข้อดีของการไม่มีเรียก super ก้อคือ เรามั่นใจได้เสมอว่า Primary Constructor ของ base class (ในที่นี้คือ Point) จะถูกเรียกเสมอ 


ในครั้งต่อไปเราจะมาดูเรื่อง abstract class และ abstract type กันครับ

1 ความคิดเห็น:

ไม่ระบุชื่อ กล่าวว่า...

Play slots online at Choegocasino Casino
Slots casino, septcasino the most dynamic and innovative gaming action in the industry. Join Choegocasino today! worrione Take your pick 카지노사이트 of slots and see how it's done.