如何在Scala的子类实例中访问超类字段?

时间:2019-04-19 12:40:34

标签: scala oop inheritance super superclass

我创建了一个抽象类(Animal),它具有一些具有具体实现的字段和方法。我创建了两个子类(Dog和Cat),它们扩展了抽象类并覆盖了超类的字段。当我尝试访问时超级类的字段出现编译错误,我无法获取超级类的字段的值。

我尝试在Cat类的子类实例中使用super关键字来获取Animal超类的年龄,但没有成功。

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

我在这里做错什么了吗?如果这样,在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)}
  }
}

1 个答案:

答案 0 :(得分:1)

尝试将var设为def,然后将替代分配替换为替代。

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)}
}