Java packages helps to resolve naming conflicts when different packages have classes with the same names. This also helps one organize files within the project.
For example, java.io package does operations related to I/O while java.net package is to do with network and so on. If we tend to put all .java files into a single package, it becomes tough to handle this package as the project gets bigger.
A 'package' can be defined as a group of related types (classes, interfaces, enumerations and annotations ) providing access protection and name space management.
Packages are used in Java in order to prevent naming conflicts, to control the access, to perform search operation and to make the use of classes, interfaces, enumerations, annotations, etc quite easier.
One can import the same package or same class multiple times. Neither compiler nor JVM complains anything about it. JVM will internally load the class only once no matter how many times one imports the same class.
A Java package is a naming context for classes and interfaces.
A package is used to create a separate name space for groups of classes and interfaces.
Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces.
'java.lang.Object' is the base class of all classes.
Casting, hierarchical and object oriented structure is the main logic behind having a single base class for all classes.
Most of the thread functionalities are specified in object class for the interthread communication.
A package in Java is a way of organizing related functionalities in a single place. In Java, File System package represents 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_JBK' in a package called 'com.javabykiran.welcome;' then it will reside under directory 'com/javabykiran/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 will create class files under same package structure.
For example maven will create 'target/classes/com/javabykiran/welcome' directory and place 'HelloWorld_JBK.class' inside that. Its mandatory that class files reside on same package or directory as declared in there source file using 'package' keyword. If failed to do this, it will result in 'java.lang.NoClassDefFoundError' in Java.
In short we can say that 'package' is a keyword in Java which is used to specify directory structure for a particular class file.
If you are using IDE like 'Eclipse' for developing your Java program then 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 good to go.
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.
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 is still the second best option and a must in order to encapsulate whole functionality rather than just a class.
The 'java.lang' package is always imported by default.
Using a package in Java is very simple. Just use the '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.
In this example we have a directory 'blog/java67/welcome' which is a 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 classpath.
package com.javabykiran.welcome
public class Hello {
public static void main(String args[]) {
System.out.println("An Example of using package com.javabykiran.welcome in Java");
}
}
Packages are considered one of the main tools for organizing code. One should put great deal of hard-work while performing various tasks say for instance naming one's package, deciding which class goes to which package etc. Also, refer Uncle Bob's (Robert C. Martin) package best practice for better architecture:
CCP (Common Closure Principle) - It is advised to put those classes together, which are likely to change together. Obviously they must be part of same functionality.
CRP (Common Reuse Principle) - It is advised to place classes based upon there re-usability aspect. It is not a good option to have a giant package with loads of classes, which cannot be reused together. Idea is to keep package small and cohesive.
Most important aspect is naming package properly, based upon their functionality. Oracle recommends following best practices and naming conventions for Java packages as mentioned below:
Programmers should use hierarchical structure to define packages and sub-packages, as used in JDK itself e.g. java.util, then java.util.concurrent, followed by java.util.concurrent.atomic or java.util.concurrent.lock etc.
Just like keeping first letter as Capital case of a Java class, packages usually should be named in lowercase letters which one can see it in Java libraries e.g. java.lang, java.util, java.io where they all use small letters.
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 their name, it is advisable to replace them with underscore.
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.
Prefer an 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 then import 'java.util.Set', where the right version will be accessed. However, if the import is implicit then import java.util.*, where 'p.Set' will be accessed.
Remember, just like class, you cannot have two packages with same name, but you can have two classes with same name in different packages. You can also have same name of sub-packages inside two different packages.
package com.javabykiran ;
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);
}
}
Predefined packages are those which are developed by SUN micro systems and are supplied as a part of JDK (Java Development Kit) to simplify the task of java programmer.
Java classes are structured into different packages based upon there functionality.
Say for instance 'java.lang' package contains classes which are essential to Java programming language e.g. Thread, Exception 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 known as the sub package of 'java.util' contains concurrent utility classes like CountDownLatch, CyclicBarrier, Semaphore etc.
Here are some of the key details to remember about package in Java programming language :
'java.lang' package is automatically imported in every Java class.
You can import all classes and its sub packages from a package by using wildcard '*'. Say for e.g. import com.abc.*
will import all classes of package com.abc as well as classes of sub packages if any.
Package must be the first statement, even before import statement in Java source file.
This is all one should know about packages in Java. We have 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 of the best practices while using package in Java application.
Good knowledge of package features is important to structure complex Java application whereas 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 use them directly, allowing you to ship a new implementation in future without affecting any client.
One can import the same package or same class multiple times. Neither compiler nor JVM complains anything about it. And the JVM will internally load the class only once no matter how many times you import the same class.
No. It is by default loaded internally by the JVM. The java.lang package is always imported by default.
No. We will have to import the sub packages explicitly. Importing 'com.bob.*' will import classes in the package 'bob' only. It will not import any class in any of its sub package’s.