Packages

How to Create PACKAGE in Java: Learn with Example Program

What is Package in Java?

A Package is a collection of related classes. It helps organize your classes into a folder structure and make it easy to locate and use them. More importantly, it helps improve re-usability.

Each package in Java has its unique name and organizes its classes and interfaces into a separate namespace, or name group.

Although interfaces and classes with the same name cannot appear in the same package, they can appear in different packages. This is possible by assigning a separate namespace to each package.

Click here if the video is not accessible 

Let’s study package with an example. We define a class and object and later compile this it in our package p1. After compilation, we execute the code as a java package.

Step 1) Consider the following code,

Creating and Using package in Java

Here,

  1. To put a class into a package, at the first line of code define package p1
  2. Create a class c1
  3. Defining a method m1 which prints a line.
  4. Defining the main method
  5. Creating an object of class c1
  6. Calling method m1

Step 2) In next step, save this file as demo.java

Creating and Using package in Java

Creating and Using package in Java

Step 3) In this step, we compile the file.

Creating and Using package in Java

The compilation is completed. A class file c1 is created. However, no package is created? Next step has the solution

Creating and Using package in Java

Step 4) Now we have to create a package, use the command

Here “..” indicates the parent directory. In our case file will be saved in parent directory which is C Drive

Creating and Using package in Java

File saved in parent directory when above code is executed.

Creating and Using package in Java

Step 7) Now let’s say you want to create a sub package p2 within our existing java package p1. Then we will modify our code as

Creating and Using package in Java

Step 9) To execute the code mention the fully qualified name of the class i.e. the package name followed by the sub-package name followed by the class name –

top
X
Welcome to Our Website
Welcome to WPBot
wpChatIcon