In Programming in Scala: A Comprehensive Step-by-Step Guide, the author said:
One way in which Scala is more object-oriented than Java is that cla
It's more object oriented in the sense that given a Scala class, every method call is a method call on that object. In Java, the static methods don't interact with the object state.
In fact, given an object a
of a class A
with the static method m()
, it's considered bad practice to call a.m()
. Instead it's recommended to call A.m()
(I believe Eclipse will give you a warning). Java static methods can't be overridden, they can just be hidden by another method:
class A {
public static void m() {
System.out.println("m from A");
}
}
public class B extends A {
public static void m() {
System.out.println("m from B");
}
public static void main(String[] args) {
A a = new B();
a.m();
}
}
What will a.m()
print?
In Scala, you would stick the static methods in companion objects A and B and the intent would be clearer as you would refer explicitly to the companion A or B.
Adding the same example in Scala:
class A
object A {
def m() = println("m from A")
}
class B extends A
object B {
def m() = println("m from B")
def main(args: Array[String]) {
val a = new B
A.m() // cannot call a.m()
}
}