JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

What is Java Static Import?


Description:

In general, any class from same package can be called without importing it. Incase, if the class is not part of the same package, we need to provide the import statement to access the class. We can access any static fields or methods with reference to the class name. Here comes the use of static imports. Static imports allow us to import all static fields and methods into a class and you can access them without class name reference.

The syntax for static imports are given below:


Code:
package com.java2novice.staticimport;
// To access all static members of a class
import static package-name.class-name.*;
//To access specific static variable of a class
import static package-name.class-name.static-variable;
//To access specific static method of a class
import static package-name.class-name.static-method;

Static Import Example:

Here we have two classes. The class MyStaticMembClass has one static variable and one static method. And anther class MyStaticImportExmp imports these two static members.



MyStaticMembClass.java
package com.java2novice.stat.imp.pac1;

public class MyStaticMembClass {

	public static final int INCREMENT = 2;
	
	public static int incrementNumber(int number){
		return number+INCREMENT;
	}
}

MyStaticImportExmp.java
package com.java2novice.stat.imp.pac2;

import static com.java2novice.stat.imp.pac1.MyStaticMembClass.*;

public class MyStaticImportExmp {

	public static void main(String a[]){
		System.out.println("Increment value: "+INCREMENT);
		int count = 10;
		System.out.println("Increment count: "+incrementNumber(count));
		System.out.println("Increment count: "+incrementNumber(count));
	}
}

Output:
Increment value: 2
Increment count: 12
Increment count: 12
Knowledge Centre
Different types of Access Modifiers
public: Any thing declared as public can be accessed from anywhere.

private: Any thing declared as private can't be seen outside of its class.

protected: Any thing declared as protected can be accessed by classes in the same package and subclasses in the other packages.

default modifier: Can be accessed only to classes in the same package.
Famous Quotations
Insanity: doing the same thing over and over again and expecting different results.
-- Albert Einstein

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2022 by Nataraja Gootooru. All Rights Reserved.