☰ See All Chapters |
How to import a class in Java
To use a class stored in one package in another package, we have to use with a fully qualified class name. Fully qualified class name means using a class with its package name.
Example:
java.util.List list = new java.util.ArrayList();
import keyword helps in importing a class stored in one package to be used in another package. If we import then we can use the class with simple name without package name.
Example:
import java.util.ArrayList;
import java.util.List;
….
List list = new ArrayList();
import statement should be used immediately after package statement. To import all the classes of a package we can use * (asterisk) character. This will be helpful when you want to you use many classes from the same package.
Example:
import java.util.*
There are disadvantages of importing all classes of package using * character. It is not a recommended approach and is not followed by good programmers.
It increases compilation time since it has to import all the members from that package.
While developing an application it would be very difficult to identify which class is coming from which package.
Example of java package and import
Eclipse project structure
We have created two packages com.java4coding.display and com.java4coding.main, and we are importing class from com.java4coding.display package to com.java4coding.main package
Demo.java
package com.java4coding.main;
import com.java4coding.display.Display;
public class Demo { public static void main(String[] args) { // This will not work if Display class is not imported Display display = new Display(); display.sayHello(); // Accessing class with fully qualified name com.java4coding.display.Display display2 = new com.java4coding.display.Display(); display2.sayHello(); } } |
Display.java
package com.java4coding.display;
public class Display { public void sayHello() { System.out.println("Hello Manu Manjunatha"); } } |
All Chapters