Scala Inheritance

Inheritance

 
Like Java, Scala supports single inheritance, not multiple inheritance.

A child (or derived) class can have one and only one parent (or base) class.

The sole exception is the root of the Scala class hierarchy, Any, which has no parent.
 

“extends” keyword should be used when a child class inherits a parent class.
 

Inheritance Example

 
Lets see an example that demonstrates inheritance in Scala.

Lets create a Parent class called Vehicle.


class Vehicle(speed:Int) {
    val mph :Int = speed
    def race() = println("Racing")
}

 
Now, lets create Child classes Car and Bike that inherit the Vehicle class.

We can override the mph and race() methods accordingly.

class Car(speed:Int) extends Vehicle(speed){
  override val mph : Int=speed
  override def race() = println("Racing Car")
}

class Bike(speed:Int) extends Vehicle(speed){
  override val mph : Int=speed
  override def race() = println("Racing Bike")
}

 
Now, inside the main method, we create a Car object and a Bike object and we then access there property mph and method race.

object HelloWorldScala {
  def main(args: Array[String]) {
   val vehicle1 = new Car(150)
    println(vehicle1.mph )
    vehicle1.race()
    
    val vehicle2 = new Bike(100)
    println(vehicle2.mph )
    vehicle2.race()
  }
}

 

Output

 
150
Racing Car
100
Racing Bike

 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags