How to Create and Import Java Packages

How to Create and Import User-Defined Packages in Java

In this article I will cover,

  • What are Java Packages?
  • Types of Java Packages
  • How to create user-defined packages and Import Java Packages
  • Sample Java Program to demonstrate the user-defined Java Packages

Video Tutorial:

A java package is a group of similar type of classes, interfaces and sub- packages.

Package in java can be categorized in two form,

  • built-in package
  • user-defined package

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Using a package in Java Program is very simple.

Just include the command package at the beginning of the program.

The syntax for declaring the package is

package name_of_package

This package statement defines the name space in which the classes are stored.

If we omit the package then the default classes are put in the package that has no name.

Basically Java creates a directory and the name of this directory becomes the package name.

Advantages of Java Packages

  1. Java package is used to categorize the classes and interfaces so that they can be easily maintained.
  2. Java package provides access protection. 
  3. Java package removes naming collision.

Importing Packages in Java

Method 1:

We import the java package class using the keyword import.

Suppose we want to use the Date class stored in the java.util package then we can write the import statement at the beginning of the program.

It is as follows –      import java.util.Date

2. Method:

There are some situations in which we want to make use of several classes stored in a package.

Then we can write it as

import java.util.*

Here * means any class in the corresponding package.

MyClass.java is a class in package MyPackage

//Java Program[MyClass.java]
 
 package MyPackage;    //include this package at the beginning
 public class MyClass 
 {
     int a;
     public void set_value(int n)
     {
         a = n;
     }
     public void display_value()
     {
         System.out.println("The value of a is: "+a);
     }
 }  

The main class named PackageDemo.java imports the package MyPackage

 //Java Program[PackageDemo.java]
  
import MyPackage.MyClass;
 //The java class MyClass is referenced here by import statement  
 public class PackageDemo 
 {
     public static void main(String args[])
     {
         MyClass obj = new MyClass();
         obj.set_value(10);
         obj.display_value();
     }
 }

Output:

The value of a is: 10

If you like the tutorial share it with your friends. Like the Facebook page for regular updates and YouTube channel for video tutorials.

Leave a Comment

Your email address will not be published.