简体   繁体   中英

Are methods of static members considered static?

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."

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.

'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);

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.*; ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM