Creating our own packages in Java with example

This tutorial is about creating our own package in Java. First, let us understand, What are the packages? A package is a collection of different classes, sub-packages and interfaces. There are different packages in Java for different purposes. There are two types of packages.

  • Built-in packages
  • User-defined packages

Built-in packages are provided as part of JDK(Java Development Kit). User-defined packages are the packages that We can create ourselves and use it in a Java program. Let’s see how we can accomplish this.

We can create a new package in Java by following the below method:

  • Use the package keyword with the desired name of the package as the first statement in your Java program. Example,
    package mypack;
  • Now create a class as public and save the program with the name same as the class name and with .java extension.
  • Create a directory with its name the same as the package name and store the java file there.
  • Now you can use this package in your program by using the import statement.

Let’s see an example.

In the given Java program, we are creating a package (name mypackage) with a class Mypack within it. We have defined a method fun() in the class Mypack.

package mypackage;

public class Mypack{
  void fun{
    System.out.println("function in mypackage.");
  }
}

Save this program as Mypack.java and store it in the directory mypackage. Now, we are ready to use this in a different Java program.

The below program shows how we can import this package and use its class. We create an instance of class Mypack and call the fun() method using this object which gives us the shown output.

import mypackage.Mypack;

class Example{
  public static void main(String args[]){
    Mypack mp = new Mypack();
    mp.fun();
  }
}

Output:

function in mypackage.

Thank you and keep coding.

Also read: File Handling in Java using NIO package

Leave a Reply