by Dinesh Thakur Category: Packages

One of the critical aims of Java and other object-oriented programming languages is that reusable classes should be created and made available to programmers so that the same code is not written repeatedly by different people. We reused the classes within a program by extending the classes and implementing the interfaces. Moreover, most of the classes that we created so far did not interact much with the outside world as they were almost self-contained, except that some of them referred to Java classes such as String from java.lang package and Scanner from java.util.lang package. However, while designing most of the real world applications, the developers write code in the form of Java classes, which eventually needs to be brought together to work as a single application.

When more than one programmer writes a more extensive application, several problems may arise such as
• There may be naming conflicts, i.e., the same class name may be given by different programmers while designing classes.
• Difficult to find the classes that are related in some way but scattered in different files/ folders.
• Cannot restrict access to your classes.
These problems can be solved using the concept of packages.

Packages In Java

A package is a collection of related classes that provides a convenient mechanism for managing a broad set of classes and prevents class name conflicts. The classes in the package are grouped by purpose or by an application. It enables you to keep your classes separated from the classes in the Java API, allow you to reuse your classes in other applications and even let you distribute your classes to others.
Java platform includes several packages that group classes according to their functionality. For example, Input/Output classes are in java. io package, utility classes in java.util package, applet classes in java.applet and so on. Each standard package name begins with java, javax, etc.

In Java, every class contained in a package including those that you have defined so far in the various programming examples. However, you never referred to any package explicitly while creating your classes. It is because you have been implicitly using the default package to hold your classes, and this does not have a name. Any class in a single directory on your hard disk that does not specify a package name are part of the default package. Using the unnamed package is acceptable for small projects, but in most cases, it is better to organize classes into named packages to provide better encapsulation.

Packages can not only contain classes but may also contain other packages. Each subpackage usually represents a smaller more specific group of classes. Packages arranged hierarchically. Each subpackage is separated from a package above it by a period (.) which indicates this subpackage is one level below the package defined above it. For example, java.util.Scanner specifies that Scanner is a class in the package util and util is a package in the package java.

Scanner is a class in the package

The package java.util indicates that the package java is at the first level. The subpackage util which is separated by a dot from is java one level below it. Moving each level down, we get more specific information about classes. So the java.util package contains utility classes.

The JDK relies on the computer hierarchical file system to manage packages. It organizes its vast collection of classes into a tree-like hierarchy of packages within packages which is equivalent to directories within directories. In other words, Java expects one to one mapping of the package name and file system directory structure. For example, in the package java. uti!, each part separated by a period (.), i.e., java and util, each correspond to a directory. The first directory is the java directory and within this directory is the subdirectory util. So the path corresponding to this package is java\util in the windows system.

Creating a Java Package

Creating a Java package is quite simple. You just need to follow the following steps.

1. Choose a package name: Naming a package is a crucial aspect of creating a package. The package name must be unique to prevent the problem of name conflicts. By convention, package names begin with a lowercase letter to distinguish them from the class names.
We shall shortly be creating a package named shapes3d which shall contain classes relating to three-dimensional shapes such as Sphere.java, Cuboid.java.

Often the companies that are involved in software development use their unique domain name to name their package — the elements in the domain name written in the reverse order to make it easier to read. For example, If the domain name of the company is ecomputernotes. com then it should place all their code into packages that have names beginning with com.ecomputernotes.

2. Pick up a base or root directory: After choosing the package name, the next step is to choose a base directory for your source tree. The base directory is the directory that contains the directories for your various packages. In our example, we use c: \javaprog as a base directory.

3. Make a subdirectory from the base directory that matches your package name: Since our package name is shapes3d so create a subdirectory named shapes3d in the base directory c:\javaprog.

4. Declaring package members: In this step, add a package declaration to the source file of each class that is part of the package. Placing a package declaration in the java source file indicates that the class declared in the file is the part of the specified package.
The package declaration must contain the keyword package followed by an identifier and a semicolon. For example, to create a package named sphere3d, use the following package declaration
package sphere3d;
The package declaration must be the first non-comment, a non-blank statement in the source file. There can be only one package statement per source file, so all classes in the source file must be in the same package.

In order to put the Sphere class in the shapes3d package, create the Sphere.java file as shown

// sphere class in shapes3d package
package shapes3d;
public class Sphere {
    double radius;
         public Sphere(double r){ radius = r;}
         public double volume(){
            return((4.0*Math.PI * radius * radius * radius)/3.0);
         }
         public double surfaceArea(){
           return(4.0*Math.PI * radius * radius);
         }
}

The Sphere class is declared public. If it is not declared public, it can only use by other classes in the same package. If you want to put several classes into the package, you have to create a separate source file for each of them because a file can have only one public class.

You can also create a hierarchy of packages. For this, you need to separate each package name from the one above it by use of a period (.). Its syntax is
package pack1.pack2 .... packN;
For example:
Package A.B; must be stored in base directory/A/B.
5. Place your source file into the package subdirectory: Once Sphere.java file has created; it is necessary to save it into the package subdirectory shapes3d. So the file Sphere.java the path
C:\javaprog\shapes3d\Sphere.java
6. Compile your source files - The next step is to compile the classes in the package as usual. So in our case, the class Sphere. java compiled using the following command.
C:\javaprog\shapes3d>javac Sphere.java
Similarly, follow the same steps for creating the Cuboid. java file and compile it.

//Cuboid class in shapes3d package
package shapes3d;
public class Cuboid {
        double length ,
width , height;
        public Cuboid(double l , double w , double h) {
            length = l; width = w; height = h;
        }
      public double volume() {
           return(length * width * height);
      }
      public double surfaceArea() {
         return(2.0 * (length * width + width * height + height * length));
      }
}

Now the file organization will look like,

packages file organization

COMPILING WITH -d(directory) FLAG

So far in our discussion, the source file and the class file were stored in the same directory. But quite often while working with projects, the source files and the class files are stored separately. In order to explain this, let us consider an example of the directory structure as shown in Fig.

From the Fig., we come to know that the source file Sphere.Java is stored in the directory path

C:\javaprog\source\shapes3d
Now if we want to store the class file Sphere.class that obtained on compiling the source file in the similar directory structure but under the classes directory then for this, you need to compile the file with -d flag. Compiling with -d flag tells the compiler not just to put your classes into the correct directory structure but also create the directories if they do not exist. The advantage of this approach is that we do not have to create the directories under the classes directory manually.

The command that helps to create the class file under the classes directory is as follows.

C:\javaprog>javac -d classes source\shapes3d\Sphere.java
After executing the above command in the classes directory, the directory shapes3d will be created which will contain Sphere.class file.





About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.