In the earlier article, we talked about predefined packages. Java, a highly user-friendly programming language permits to create our own packages and use the same in programming. In a project where different developers are involved in different modules and tasks, creating packages is unavoidable, mainly for avoiding name duplication. Besides, package naming conventions will help to identify the applications developed by a single developer or a team easily.
Steps of Creating User Defined Packages in Java
- Creating a package with a .Class file
- Setting a Classpath from the target directory (The directory from which you would like to access it.)
- Writing a program using files from the package.
Create User Defined Package in Java
Here we are assuming that “C:\Snr” is the target directory where the package will be created.
public class Tiger
public void getDetails(String nickName, int weight)
System.out.println(“Tiger nick name is ” + nickName);
System.out.println(“Tiger weight is ” + weight);
The package is a keyword in Java and it is followed by the package name can create a new package. However, while creating user defined packages in Java, an order of the statement is very important and it is as follows.
- Package Statement
- Import Statement
- Class Declaration
If there are any changes in the above order, then it will be a compilation error.
Once the code is ready the next step is a compilation and it should be with package notation. Package notation uses -d compiler option as follows
C:\snr > javac -d . Tiger.java
Here, the compiler d will create a new folder called “Forest” and put the class “Tiger” in it.
Using User Defined Packages in Java
Once a user-defined package is created the next step is to use it. You will have to create a classpath for it first. Classpath is an environment variable which provides the address of the directory to the OS. Now you can write a program the target directory and access the package.