Java Static import

Static import is a feature that provides the facility to access static members of a class directly without using a class name.

Java Static import Example

package com.w3schools.display;

public class Display {
        public static void displayText(String text){
               System.out.println(text);
        }
}
package test;

import static com.w3schools.display.Display.*;

public class Test {
       public static void main(String args[]){
              displayText("Hello W3schools360.com!");
       }
}

Output

Hello W3schools360.com!

Advantages of static import

It reduces the code by removing the need for a class name to access static data members.

Disadvantages of static import

  1. Static import reduces the code readability because of class name absence.
  2. If two classes have static data members with the same name and both classes are statically imported. Then Java will throw a compile-time error.

Import vs static import in Java

            import                static import
  1. It provides the feature to access classes and interfaces without package names.
  2. Accessibility is for classes and interfaces.
  3. import does not result in an unreadable code.
  4. No code conflict.
  1. It provides the feature to access static members without class and interface names.
  2. Accessibility is for static data members.
  3. Static import can result in an unreadable code.
  4. Code conflict can occur.

 

Please follow and like us:
Content Protection by DMCA.com