I'm would like to know how could I inherent static field from Java class in Scala.
Here is a Java example, if I a class named ClassFromJava, I could extend it, add some static field, and use the subclass to access the VERSION field.
public class ClassFromJava {
public static int VERSION = 1;
}
public class ClassFromJavaSub extends ClassFromJava {
public static String NOTE = "A note";
}
public class Test {
public static void main (String [] args) {
System.out.println (ClassFromJavaSub.VERSION); // This works.
}
}
But if I want extends ClassFromJava in Scala, and add some constant value, it seems not work.
object ClassFromScala extends ClassFromJava {
val NOTE = "A Note"
}
object Test {
def main (args: Array[String]) {
// This line won't compile
// ClassFromScala has no value VERSION.
println (ClassFromScala.VERSION)
}
}
What should I do if I would like ClassFromScala also has the VERSION variable?
Objects and classes are not completely decoupled. An object can extend another class, making its fields and methods available in a global instance. The reverse is not true, however, because an object cannot itself be extended.
It can be accessed without instantiating the outer class, using other static members. Just like static members, a static nested class does not have access to the instance variables and methods of the outer class. You can extend static inner class with another inner class.
In Scala, we use class keyword to define instance members and object keyword to define static members. Scala does not have static keyword, but still we can define them by using object keyword. The main design decision about this is that the clear separation between instance and static members.
In Scala there are no static methods: all methods are defined over an object, be it an instance of a class or a singleton, as the one you defined in your question.
object ClassFromScala extends ClassFromJava {
def VERSION = ClassFromJava.VERSION
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With