Scala – Inheritance

  • date 8th October, 2020 |
  • by Prwatech |
  • 0 Comments

Types of Inheritance:

·  Single Level Inheritance

·  Multi-level Inheritance

·  Hierarchical Inheritance

·  Multiple Inheritance: It cannot be achieved by Classes. It can be achieved by using Traits.

Note: Two Classes cannot be extended by one class at the same time.

·  Hybrid Inheritance

An Example program to portray Single level inheritance:

package single

class single_lvl {

  val prop:Double = 3000.00

  protected var area_house:Double = 2000.00

  def house() : Unit = {

       println(“Villa is built over ” + area_house + ” sq ft.”)

  }

}

class Child_A extends single_lvl{

  def child_house() : Unit = {

    println(“Child house is built in area of ” + (prop-area_house) + ” sq ft.”)

  }

}

object SCA{

  def main(args: Array[String]): Unit = {

    val c = new Child_A()

    c.child_house()

    c.house()

    println(“Single Inheritance Implemented”)

  }

}

 

An Example program to portray Multi level inheritance:

package inheritence

class Multi_lvl {

    def run(): Unit = {

      println(“Running everyday 3kms is good for health”)

    }

}

class AM extends Multi_lvl{

    def walk(): Unit = {

      println(“Walking Early Morning leads to Healtier life”)

    }

}

class BM extends AM{

   println(“Both parent and grand-parent method can be accesed from here”)

}

object ABM{

  def main(args:Array[String]):Unit = {

     val b = new BM()

     b.walk()

     b.run()

  }

}

 

0
0

Quick Support

image image