10 Things Every Java developer Should Know about Package concept

What is package in Java
package in Java is a way to organize related functionality in single place. If you look at File System package in Java represent a directory where Java source file is stored in compilation and class files are stored after compilation. For example, if you create a class HelloWorld in a package called com.java67.welcome; then it will reside under directory com/java67/welcome in the source tree and you can view that in your IDE like Eclipse or Netbeans or even by navigating to file system. once you compile your Java program either by using your IDE, Ant build Script or maven compile plugin; it creates class files under same package structure. For example, maven will create target/classes/com/java67/welcome directory and place HelloWorld.class inside that. Its mandatory that class files reside on same package or directory as declared in there source file using package keyword, failure to do will result in java.lang.NoClassDefFoundError in Java. In summary answer of the question What is package in Java can be as simple as that package is a keyword in Java which is used to specify directory structure for the particular class file.

How to create package in Java

If you are using IDE like Eclipse for developing your Java program than you don't need to do anything. Just click on the new-->package and Eclipse will ask you the name of the package, put the name of the package and you are done. Now if you want to create Java class on that package, just select  the package in the package explorer and create new-->Java Class. If you are not using any IDE then you manually need to create directories corresponding to package in Java.

Why use package in Java

A package provides Encapsulation in Java program. default access modifier for any variable or class is package-private i.e. they are only visible into the package, on which they are declared. By using the package you Encapsulate whole functionality which allows you to change the functionality, include new functionality or just change the implementation without breaking the whole application. Though package is not the highest degree of Encapsulation in Java which is achieved using a private keyword, it still second best option and must encapsulate whole functionality rather than just a class.

How to use package in Java

Using package in Java is very simple. just use package keyword along with the name of the package at the top of your Java source file to declare a package in Java. package declaration must be the first line in Java source file even before import statement. here is an example of how to use a package in Java

package blog.java67.welcome

public class Hello{
    public static void main(String args[]){
         System.out.println("An Example of using package in Java");


In this example, we have a directory blog/java67/welcome, which is package and Hello.java class is stored under it. When Java compiler will compile this class, it will verify whether this particular class is stored as  /blog/java67/welcome/Hello.java, which is relative to classpth.

Best Practices while Using Package in Java Program

Packages are also your main tool for organizing code. You should put a great deal of hard-work while naming your package, deciding which class goes to which package etc. Also, try to follow Uncle Bob's (Robert C. Martin) package best practice for better architecture :

1) CCP (Common Closure Principle) - Advise putting classes together, which are likely to change together. Obviously, must be part of the same functionality.

2) CRP (Common Reuse Principle) - Advise putting classes based upon there re-usability aspect. It advises against a giant package with loads of classes, which can not be reused together. Idea is to keep package small and cohesive.

Most important is naming package properly, based upon functionality.  Oracle recommends following best practices and naming conventions for Java packages :

1) Programmers should use hierarchical structure to define packages and sub-packages, as used in JDK itself e.g. java.util, then java.util.concurrent, then java.util.concurrent.atomic or java.util.concurrent.lock etc.

2) Just like keeping the first letter as Capital case of a Java class, packages usually use all lowercase letters, you can see it through Java libraries e.g. java.lang, java.util, java.io they all use small letters.

3) One example of creating a package for a product in a company to define some features can be com.prod.features. If product or company has a hyphen in there name, replace them with an underscore.

4) packages and classes should not be dependent on each other in a cyclic manner because cyclic dependencies make it difficult to understand and modify a software system.

5) Prefer explicit import, identifying the particular classes imported over implicit import using a wildcard, by using * operator to include all classes from a package. Explicit import is better than implicit import as it cannot be misinterpreted. The precedence of Java imports (explicit, package, wildcards) is not well known and often misused leading to hard to find and understand problems. Also, using explicit imports result in a precise list of all dependencies. This makes it easier to comprehend how dependent a class is in other classes (the higher dependency, the more complex the class). Consider the scenario where a programmer has defined a class Set in a package pkg . Consider now that someone else attempts to define a class UseSet in package pkg, which intends to use Java's own java.util.Set (and not p.Set). If the import is explicit, hence import java.util.Set, then the right version
will be accessed. However, if the import is implicit, hence import java.util.*, then p.Set will be accessed

package pkg ;

import java.util.HashSet; // ok
import java.util.Set; // ok
//import java.util.*; // this would not be ok

public class UseSet {
private Set set = new HashSet();

public void addElement(int i) {

Remember, just like class, you can not have two packages with the same name, but as you can have two classes with the same name in different packages, you can also have the same name of sub-packages inside two different packages.

Predefined package in Java

Package in Java What Why and Best Practices Example Tutorial

                                                                                                                                                                                                                                                                                                                All the Java classes are structured into a different package based upon there functionality for example java.lang package contains classes which are essential to Java programming language e.g. ThreadException Error, Object etc. On the other hand package like java.util contains all utility classes e.g. Collection classes, Scanner, and other utility.  java.io package contains Java classes related to Input and Output functionality. java.util.concurrent also called sub package of java.util contains Concurrent utility classes like CountDownLatchCyclicBarrierSemaphore etc

Things to know about Package in Java

Here are some of the key details to remember about package in Java programming language :

1) java.lang package is automatically imported in every Java class.

2) You can import all classes and sub packages from a package by using wildcard * e.g. import com.abc.* will import all classes on package com.abc as well as classes on any sub package.

3) package must be the first statement, even before import statement in Java source file.

That's all you should know about a package in Java. We have gradually learned from basic like what is package in Java, Why should we use a package in Java and how to use a package in Java to some best practices while using a package in Java application. Good knowledge of package feature is important to structure complex Java application and clever use of package-private encapsulation can lead to highly flexible and maintainable software.

One example of clever use of package is java.util.EnumSet class, which is abstract and both of its implementation JumboEnumSet and RegularEnumSet are package-private. Since the instance of EnumSet is created via factory methods and these classes are package-private, there is no way a client can use them directly, allowing you to ship a new implementation in future without affecting any client. A simple example of a package as shown in above Java program is enough to make you going and explores how Java source file and class file organize into a package.

Further Learning
Data Structures and Algorithms: Deep Dive Using Java
Java Fundamentals: The Java Language
Complete Java Masterclass

Other Java tutorials from java67 blog
Difference between TreeSet and HashSet in Java
Difference between HashMap and ConcurrentHashMap in Java

No comments:

Post a Comment