Are methods of static members considered static?

110 Views Asked by At

In the following static import example from pg. 16 of the Oracle OCA/OCP Java SE 7 Programmer I and II Study Guide:

import static java.lang.System.out;              // 1
import static java.lang.Integer.*;               // 2
public class TestStaticImport {
  public static void main(String[] args)  {
    out.println(MAX_VALUE);                      // 3
    out.println(toHexString(42));                // 4
  }
}

The book says of the line marked 3:

"Now we’re finally seeing the benefit of the static import feature! We didn’t have to type the System in System.out.println! Wow! Second, we didn’t have to type the Integer in Integer.MAX_VALUE. So in this line of code we were able to use a shortcut for a static method AND a constant.

Is it an error to refer to println as a static method here?

The program above is given as shown in the text.

For the line marked 4, the book says: "Finally, we do one more shortcut, this time for a method in the Integer class."

3

There are 3 best solutions below

0
On BEST ANSWER

Quoted from the book:

  1. Now we’re finally seeing the benefit of the static import feature! We didn’t have to type the System in System.out.println! Wow! Second, we didn’t have to type the Integer in Integer.MAX_VALUE. So in this line of code we were able to use a shortcut for a static method AND a constant.

Your criticism is valid. In that line of code, we are NOT using a shortcut for static method. It is just a shortcut to a static field instead.

0
On

'import static' can only refer static members of a Class.
So here it is refering 'out' Object from System class.
In System class 'out' is defined as

  public final static PrintStream out = null;

println() is non static method of java.io.PrintStream class.

So here 'import static' is nothing to do with println() it is only refering 'out' object.
And 'out' is further refering to println().

Same with Integer class. it is importing all static methods and variables of Integer class. So you can call it directly as

out.println(MAX_VALUE);  

instead of

out.println(Integer.MAX_VALUE);
8
On

The method being referred to as static is toHexString, not println. What that line means is that they were able to import toHexString and MAX_VALUE with a single statement (import static java.lang.Integer.*;).