This is ericpony's blog

Tuesday, April 16, 2013

Static abstract methods in Java

In Java 6 and earlier, you can't define an abstract static method. For example,
abstract class foo {
    abstract void bar( );        // this is ok
    abstract static void bar2(); // this gives a compile-time error
}
Abstract static methods work fine and are commonly used in many other languages, e.g., @classmethod in Python. Indeed, some methods just don't make sense as instance methods, and it would be much more effective to call directly a static abstract method than creating an instance just for using that abstract method. If Java supported abstract static methods, one could expect that the method (i) must be implemented by subclasses, and (ii) is a class method of the subclass. In Java, however, a static method cannot be inherited or overridden. If a subclass has a static method with the same signature as a static method in the superclass, the former shadows the latter instead of overriding it. (See this document for rules of overriding and shadowing in Java.)
On the other hand, some languages do support static inheritance, just like the way they support instance inheritance. From a syntax perspective, those languages usually require the class name to be included in the statement. For example, in Java, assuming you are writing code in ClassA, where methodA is a static method and there is no instance method with the same signature. Then methodA() and ClassA.methodA() are equivalent statements. In SmallTalk, however, the class name is not optional, so the syntax is (note that SmallTalk does not use the . to separate the "subject" and the "verb", but uses it as the statement terminator): ClassA methodA. Because the class name is always required, the correct "version" of the method can always be determined by traversing the class hierarchy.
Since a Java static method defined in an abstract class would belong to that very class, an abstract static method could not be used anyway. Fortunately, an abstract class can have static fields and static methods starting from Java 7 (see this document). These static members can be invoked with a class reference as you would do with a non-abstract class.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...