Open In App

User-Defined Packages in Java

Last Updated : 06 Aug, 2025
Comments
Improve
Suggest changes
18 Likes
Like
Report

User-defined packages are those packages that are designed or created by the developer to categorize classes and packages. It can be imported into other classes and used in the same way as we use built-in packages. But if we omit the package statement, the class names are put into the default package, which has no name.

To create a package, we're supposed to use the package keyword.

Syntax:

package package-name;

Steps to Create User-defined Packages

Step 1: Creating a package in a Java class. The format is very simple and easy. Just write a package by following its name.          

package example1;

Step 2: Include the class in a Java package, but remember that a class only has one package declaration.

package example1;
class Geeks {
public static void main(String[] args){
-------function--------
}
}

Step 3: Now the user-defined package is successfully created, we can import it into other packages and use it's functions.

Note: If we do not specify any package for a class, it is placed in the default package.

In the below-mentioned examples, in the first example we'll create a user-defined package name "example" under that we've class named "Geeks" which has a function to print message. In the second example, we will import our user-defined package name "example" and use a function present in that package.

Example 1: In this example, we will create a user-defined package and function to print a message for the users.

Java
package example;

// Class
public class Geeks {

    public void show()
    {
        System.out.println("Hello geeks!! How are you?");
    }

    public static void main(String args[])
    {
        Geeks obj = new Geeks();
        obj.show();
    }
}

Output:

Hello geeks!! How are you?

Example 2: In the below-mentioned example, we will import the user-defined package "example" created in the above example. And use the function to print messages.

Java
import example.Geeks;

public class Test {
    public static void main(String args[])
    {
        Geeks obj = new Geeks();
        obj.show();
    }
}

Output:

Hello geeks!! How are you?

Explanation:

  • A user-defined package example contains a class Geeks.
  • Geeks class has a show() method that prints "Hello geeks!! How are you?".
  • Another program imports the example package and calls the show() method.
  • Both programs display the same greeting, showing successful package reuse

Article Tags :

Explore