Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance with Scala 'object'

Tags:

java

object

scala

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 it does in Scala, but can't seem to find how to write the 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 doesn't compile. It is because object can't inherit ?

like image 328
OscarRyz Avatar asked Jun 06 '11 17:06

OscarRyz


1 Answers

You can only extend from classes. So you might wanna change Super to be a class instead of an object

Also, you need to add the override keyword to the method you plan to override.

See "Method Overriding" here

like image 198
Pablo Fernandez Avatar answered Sep 21 '22 04:09

Pablo Fernandez