Search code examples
scalaoopinheritancesupersuperclass

How to access super class fields in a child class instance in scala?


I have created an abstract class (Animal) having some fields and methods having concrete implementations.I have created two child classes(Dog and Cat) extending the abstract class and overriding the fields of super class.When i am trying to access the fields of super class i am getting compilation error and i am unable to fetch the value of super class field.

I tried using the super keyword in the child class instance of Cat class to fetch the age of Animal super class but it didnt worked out.

def superPrnt{println(super.age)}
compilation error:
/home/jdoodle.scala:32: error: super may not be used on variable age
   def superPrnt{println(super.age)}
                           ^
one error found
Command exited with non-zero status 1

Am i doing something wrong here and if then what is the correct way of accessing super class field values in a child class instance in scala?

object MyClass {

  def main(args: Array[String]) {
      val dog=new Dog("s")
      dog.sayHello
      println(dog)
      val cat =new Cat("nancy")
      cat.sayHello
      println(cat)
      cat.superPrnt
     //cat.age=12
     //cat.greeting="nhj"
     //println(cat)
  }
  abstract class Animal() {

      val greeting:String="boo"
      var age:Int=5
      def sayHello{println(greeting)}
      override def toString=s"I say $greeting and i am $age years old"

  }
  class Dog(name:String) extends Animal {
      override val greeting="woof"
      age=2
  }
  class Cat(name:String) extends Animal{
      override val greeting="meow"
      age=4
      def superPrnt{println(super.age)}
  }
}

Solution

  • Try to make var a def and replace re-assignment with overriding.

    abstract class Animal() { 
      val greeting:String="boo"
      def age:Int=5
      def sayHello{println(greeting)}
      override def toString=s"I say $greeting and i am $age years old"
    }
    
    class Dog(name:String) extends Animal {
      override val greeting="woof"
      override def age=2
    }
    
    class Cat(name:String) extends Animal{
      override val greeting="meow"
      override def age=4
      def superPrnt{println(super.age)}
    }