Inheritance with Scala 'object'

I have this Java code:

class Super {
    public static void foo() { bar(); }
    public static void bar() { out.println("BAR");}

    public static void main(String[] args) {
        foo();
    }
}
class Sub extends Super {
    public static void bar() { out.println("bar"); }
}

And I would like to see what he does in Scala, but cannot find how to write an equivalent. This is what I have:

object Super  {
  def foo() { bar() }
  def bar() { println("BAR")}
  def main( args : Array[String]) {
    foo()
  }
}
object Sub extends Super {
  override def bar() { println("bar")}
}

But it does not compile. Is it because an object cannot inherit?

+3
source share
2 answers

You might want to change it to something like this

class Super {
  def foo() { bar() }
  def bar() { println("BAR")}
  def main( args : Array[String]) {
    foo()
  }
}

object Super extends Super {
}

object Sub extends Super {
  override def bar() { println("bar")}
}

So you have a Super type and a Super object.

EDIT: just moved the main method to the Super class, so it became cleaner.

+8
source

You can only extend classes. Therefore, you can change Superhow classinsteadobject

In addition, you need to add a keyword overrideto the method that you plan to override.

. " "

+3

All Articles