Java Package and Static Import

Java Package as the name suggest packaging multiple related java files in to one folder and Static import allows us to access method without using the fully qualified name.

There are two type of packages in java:

  1. User defined package (user creates these packages while development).
  2. Built in package given by Java (e.g. java.lang, java.util etc.)

Syntaxt:

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:

  1. A class can have only one package statement in the same class.
  2. A class can have multiple import statement in java depending on the usage.
  3. Packages helps us to keep all the similar class in one package.
  4. We can have classes with the same name in different packages.

Rules:

  1. 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

Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.

  • Languages: Java, Python
  • Frameworks: J2EE, Spring, Struts 2.0, Hibernate
  • Web Technologies: React, HTML, CSS
  • Analytics: Adobe Analytics
  • Tools & Technologies: IntelliJ, JIRA

🌐 LinkedIn

📝 Blogs

📧 Imran Khan