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 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开发者_开发问答 ?
You might want to change it into 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")}
}
This way you have both the type Super and the object Super.
EDIT : Just moved the main method to class Super, that way it is cleaner.
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
精彩评论