Saturday, August 25, 2012

What you should know about Package in Java - Best Practices, Tutorial and Howto Example

What is package in Java
package in Java is a way to organize related functionality in single place. If you look on File System package in Java represent a directory where Java source file is stored before compilation and class files are stored after compilation. For example if you create a class HelloWorld in a package called com.java67.welcome; than it will reside under directory com/java67/welcome in 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 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 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 new-->package and Eclipse will ask you name of the package, put name of the package and you are done. Now if you want to create Java class on that package, just select  the package in package explorer and create new-->Java Class. If you are not using any IDE than you manually need to create directories corresponding to package in Java.

Why use package in Java

package provides Encapsulation in Java program. default access modifier for any variable or class is package-private i.e. they are only visible into package, on which they are declared. By using package you Encapsulate whole functionality which allows you to change the functionality, include new functionality or just change the implementation without breaking whole application. Though package is not the highest degree of Encapsulation in Java which is achieved using private keyword, it still second best option and must to 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 name of package at top of your Java source file to declare package in Java. package declaration must be first line in Java source file even before import statement. here is an example of how to use 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");
    }

}


Best Practices while Using Package in Java Program

Packages are also your main tool for organizing code. You should put 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 same functionality.

2) CRP (Common Reuse Principle) - Advise to put classes based upon there re-usability aspect. It advice 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 first letter as Capital case of a Java class, packages are 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 package for a product in a company to define some features can be com.prod.features. If product or company has hyphen in there name, replace them with 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 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 on 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) {
   set.add(i);
}
...
}

Remember, just like class, you can not have two packages with same name, but as you can have two classes with same name in different packages, you can also have 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 in to 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 first statement, even before import statement in Java source file.



That's all you should know about package in Java. We have gradually learned from basic like what is package in Java, Why should we use package in Java and how to use package in Java to some best practices while using 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 instance of EnumSet is created via factory methods and these classes are package-private, there is no way client can used them directly, allowing you to ship a new implementation in future without affecting any client. Simple example of package as shown in above Java program is enough to make you going and explores how Java source file and class file organize into package.


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


No comments:

Post a Comment

Java67 Headline Animator