Friday, December 16, 2011

Class Definition » Static Import

Static import

In Java 5 you can import static fields using the import static keywords.
Before Java 5, to use a static final field in the Calendar class, you must first import the Calendar class.
import java.util.Calendar;
Then, you can use it by using the notation className.staticField.
if (today == Calendar.SATURDAY)
In Java 5, you can do
import static java.util.Calendar.SATURDAY;

if (today == SATURDAY)
 
 
Static importing the Math Class Methods

import static java.lang.Math.sqrt;

public class MainClass {

  public static void main(String[] arg) {
    System.out.println(sqrt(2));
  }

}
1.4142135623730951
 
 
Use static import to bring sqrt() and pow() into view.

import static java.lang.Math.pow;
import static java.lang.Math.sqrt;

class Hypot {
  public static void main(String args[]) {
    double side1, side2;
    double hypot;

    side1 = 3.0;
    side2 = 4.0;

    hypot = sqrt(pow(side1, 2+ pow(side2, 2));

    System.out.println("Given sides of lengths " + side1 + " and " 
 + side2 + " the hypotenuse is "
        + hypot);
  }
}
 
http://www.java2s.com/Tutorial/Java/0100
__Class-Definition/Catalog0100__Class-Definition.htm
 

No comments:

Post a Comment