Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala object extends Java class static field

Tags:

java

scala

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?

like image 352
Brian Hsu Avatar asked Oct 05 '10 13:10

Brian Hsu


People also ask

Can an object extend a class Scala?

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.

Can a class extend a static class?

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.

Can Scala classes contain static members?

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.

Are there static methods in Scala?

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.


1 Answers

object ClassFromScala extends ClassFromJava {
  def VERSION = ClassFromJava.VERSION
}
like image 157
Rex Kerr Avatar answered Oct 11 '22 16:10

Rex Kerr