Monday, 21 September 2020

Scala: Inheritance

 

Syntax

class ChildClass(properties) extends SubClass(properties){

 

}

 

Example

class Employee(id: Int, name: String){
	
	override def toString() = s"id = $id, name = $name"

}

class Manager(id: Int, name: String, noOfReportees: Int) extends Employee(id, name){
	
	override def toString() = {
		val msg = super.toString
		s"$msg, noOfReportees = $noOfReportees"
	}

}

scala> class Employee(id: Int, name: String){
     |  
     |  override def toString() = s"id = $id, name = $name"
     | 
     | }
class Employee

scala> 

scala> class Manager(id: Int, name: String, noOfReportees: Int) extends Employee(id, name){
     |  
     |  override def toString() = {
     |      val msg = super.toString
     |      s"$msg, noOfReportees = $noOfReportees"
     |  }
     | 
     | }
class Manager

scala> 

scala> val manager = new Manager(1, "Anand", 18)
val manager: Manager = id = 1, name = Anand, noOfReportees = 18

scala> 

scala> println(manager)
id = 1, name = Anand, noOfReportees = 18

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment