Search code examples
scalainheritanceinstancemember

How to access members of super class using an instance of the sub class


I am practicing this code from JavaTpoint for learning inheritance in Scala. But I cannot access the member Bike from the class Vehicle who's value is initialised to zero. I tried by supertype reference but it still shows the overriden value. Can you tell how can I access the value speed = 0 using an instance of Bike class. here is the code and the output. Thanking in advance.

   class Vehicle{  
  val speed = 0
  println("In vehicle constructor " +speed)
    def run(){  
        println(s"vehicle is running at $speed")  
    }  
}  

class Bike extends Vehicle{  
  override val speed = 100
     override def run(){  
     super.run()
        println(s"Bike is running at $speed km/hr")  
    }  
}  

object MainObject3{  
    def main(args:Array[String]){  
      var b = new Bike()  
        b.run()  
        var v = new Vehicle()
        v.run()
        var ve:Vehicle=new Bike()
      println("SuperType reference" + ve.speed) 
    ve.run()
    }  
} 

How do I get the result using instance of Bike.


Solution

  • I can think of two options.

    1) Save the value before overriding it.

    class Bike extends Vehicle{
      val oldspeed = speed
      override val speed = 100
      override def run(){
        println(s"Vehicle started at $oldspeed km/hr")
        println(s"Bike is running at $speed km/hr")
      }
    }
    

    2) Make the value a def in the base class. Then it can be accessed in the sub-class.

    class Vehicle{
      def speed = 0
      def run(): Unit = {...}
    }
    
    class Bike extends Vehicle{
      override val speed = 100
      override def run(){
        println(s"Vehicle started at ${super.speed} km/hr")
        println(s"Bike is running at $speed km/hr")
      }
    }