Java is the future !: Static method invocation without using class name

Tuesday, October 5, 2010

Static method invocation without using class name

Question : Can we call a static method without mentioning the class name in Java?

Answers : 


You may be interested in static imports. You have to mention the class name in the import statement, but after that you don't have to.e.g. from the linked article:
import static java.lang.Math.abs;
import static java.lang.Math.max;
int xDist = abs(destination.getX() - x);
int yDist = abs(destination.getY() - y);
return max(xDist, yDist);
Introduced in Java 5.
answered Apr 13 at 12:35


Yes, you can call a static method without mentioning the class name. There's the import static(see JLS 7.5.4 for exact mechanism), but even without it, if the name can be resolved (see JLS 15.12.1for exact mechanism) without fully qualifying the class, it will work.
The following code compiles and prints "Hello world!" as expected.
import static java.lang.System.out;
public class Test {
   static String greeting() {
      return "Hello world!";
   }
   public static void main(String[] args) {
      out.println(greeting());
   }
}
out in the println statement is actually a static field access of the class java.lang.System, not a static method, but it's a static member access nonetheless. greeting() is a staticmethod invocation, and the class name can be omitted since its reference can be resolved without fully qualifying the name.

Now let's ask if this is a good idea. Unless you're calling a static method from within its class, IT'S NOT a good idea generally to omit the class name!!!
Let's focus on static import first. A quote from the guide:
So when should you use static import? Very sparingly! Only use it when you'd otherwise be tempted to declare local copies of constants, or to abuse inheritance (the Constant Interface Antipattern). In other words, use it when you require frequent access to static members from one or two classes. If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import. Readers of your code (including you, a few months after you wrote it) will not know which class a static member comes from. Importing all of the static members from a class can be particularly harmful to readability; if you need only one or two members, import them individually. Used appropriately, static import can make your program more readable, by removing the boilerplate of repetition of class names.
The case is made stronger by the following example:
class Base {
    void task1() {
        System.out.println("Base.task1");
    }
    static void task2() {
        System.out.println("Base.task2");
    }
}
class Child extends Base {
    void task1() {
        System.out.println("Child.task1");          
    }
    static void task2() {
        System.out.println("Child.task2");
    }       }
//....
Base sweetChildOMine = new Child();
sweetChildOMine.task1(); // prints "Child.task1"
sweetChildOMine.task2(); // prints "Base.task2"
What a surprise! You'd think that since sweetChildOMine has a reference to an instance of Child,sweetChildOMine.task2() should print "Child.task2" because it's overridden by Child class, right?
WRONG! A static method can not be overridden! It can only be hidden by a subclass! In fact, if you tried to do the right thing and add the @Override annotation to task2, it would not compile!
If the invocation mode is static, no target reference is needed and overriding is not allowed. Method m of class T is the one to be invoked.
In fact, this problem is covered in Java Puzzlers Puzzle 48: All I Get Is Static. The conclusion given at the end of the puzzle is this:
In summary, qualify static methods invocations with a class name, or don't qualify them at all if you're invoking them from within their own class, but never qualify them with an expression. Also, avoid hiding static methods. Together, these guidelines help eliminate the misleading appearance of overriding with dynamic dispatch for static methods.
It is best to follow all these recommendations together, so:
  • If you're calling a static method within its own class, don't qualify
  • Otherwise, qualify with the class name
    • If you're doing this a lot within one class, consider static import of that specific method
      • Try not to static import all members with *
    • Never qualify with an expression
  • Don't hide a static method; you can't @Override it, it'll only cause confusion

See also:

answered Apr 13 at 13:23

No comments:

Post a Comment