Importing Package and Class, Static Imports, Creating a Package

Filter Course


Importing Package and Class, Static Imports, Creating a Package

Published by: Dikshya

Published date: 02 Jul 2023

Importing Package and Class, Static Imports, Creating a Package

Importing Package and Class:

In Java, you can import packages and classes to make them accessible in your code. The import statement is used for this purpose. Here's an example:

import java.util.ArrayList;
import java.util.List;

public class MyClass {
    public static void main(String[] args) {
        List myList = new ArrayList<>();
        // Use the ArrayList and List classes here
    }
}

In this example, we import the java.util.ArrayList and java.util.List classes using the import statement. It allows us to use these classes directly in our code without specifying the full package name.

Static Imports:

Java also allows static imports, which allow you to access static members of a class without qualifying them with the class name. To use static imports, you need to use the import static statement. Here's an example:

import static java.lang.Math.PI;
import static java.lang.Math.cos;

public class MyClass {
    public static void main(String[] args) {
        double result = cos(PI / 4);
        // Use the Math.PI and Math.cos methods here
    }
}

In this example, we import the static members PI and cos from the java.lang.Math class. It allows us to directly use PI and cos without qualifying them with the class name.

Creating a Package:

To create a package in Java, you need to follow these steps:

  1. Choose a package name: Package names usually follow the reverse domain name convention, such as com.example.myapp. This helps ensure uniqueness and avoids naming conflicts.

  2. Create a directory structure: Create a directory structure that matches the package name. Each directory represents a level in the package hierarchy. For example, if the package is com.example.myapp, create the directories com/example/myapp.

  3. Add classes to the package: Place your Java class files in the corresponding directory of the package.

  4. Specify the package declaration: At the beginning of each Java class file, include the package statement to specify the package to which the class belongs. For example, package com.example.myapp;.

Here's an example:

package com.example.myapp;

public class MyClass {
    // Class members and code here
}

In this example, we define a class named MyClass that belongs to the com.example.myapp package. The class file should be placed in the com/example/myapp directory.