Java Package and Static Import
Java Package
Package as the name suggest packaging multiple related java files in to one folder.
There are two type of packages in java:
- User defined package (user creates these packages while development).
- Built in package given by Java (e.g. java.lang, java.util etc.)
Syntax:
Below is the example for importing a package inside class:
import java.util.List;
java: java is a top level package.
util: util is sub level and child package of java.
List: List is a class defined in java.
Example:
In the above code snippet we have Calculator and TestClass from two different packages. We can access Calculator class inside com.project.core.main using import statement.
Note:
- A class can have only one package statement in the same class.
- A class can have multiple import statement in java depending on the usage.
- Packages helps us to keep all the similar class in one package.
- We can have classes with the same name in different packages.
Rules:
- Package can have multiple classes to import the same we can user two different statements given below:
a. We can import all the classes using * (asterisks ).e.g.
import com.test.package.*;
b. We can import only required class using below startment:
import com.test.package.class_name_1;
import com.test.package.class_name_2;
2. How we can access, if we have class(TestClass) with the same name in different package.
Import com.project.package.first.*;
Import com.project.package.second.*;
first.TestClass firstTestClass = new first.TestClass();
second.TestClass firstTestClass = new second.TestClass();
Static Import
Static import allows us to access method without using the fully qualified name.
We can make our statement shorter using static import.
Note: Use static import in case we are using a lot of static members and variables.
Code without static import:
Code with static import:
Imran Khan, Adobe Community Advisor, AEM certified developer and Java Geek, is an experienced AEM developer with over 11 years of expertise in designing and implementing robust web applications. He leverages Adobe Experience Manager, Analytics, and Target to create dynamic digital experiences. Imran possesses extensive expertise in J2EE, Sightly, Struts 2.0, Spring, Hibernate, JPA, React, HTML, jQuery, and JavaScript.