Creating and Using Packages in Java

In this class, We discuss Creating and Using Packages in Java.

The reader should have prior knowledge of object-oriented programming concepts. Click Here.

Package: A package is a folder.

Why do we need packages?

Suppose we have written many mathematics-related classes, and we place all those classes in a package.

We place all the classes related to the network in a network package.

Inside a package, we can create one more package called a subpackage.

We can create Any number of levels of packages.

File: test.java

Package p1;

class A

{

}

class test

{

}

We created classes “A” and “test” in the above program.

In the first line, we mentioned package p1;

When we compile the above file, package p1 is created. And the class files A.class and “test.class” are in package “p1”.

We use “javac -d . test.java” to compile a Java file with a package.

We are adding one more class to package p1.

Take a file test2.java.

File: test2.java

package p1;

class test2

{

}

When we compile the file “test2,” the “test2.class” file will be moved to package “p1”

The package “p1” already exists, so the “test2.class” will be placed in package “p1”.

I am using classes from package p1.

We use the “import” keyword to access classes in the package.

Take a new file test5, java

import p1.*;

class C extends A

{

}

We import all the classes in package “p1”.

We can use the classes after importing.

To import all the packages, we use the “*” symbol.

Accessing classes from sub-packages.

import p1.p5.*;

In the p1 package, we have a p5 subfolder.