Differentiation of Packages in Java

If you are interested to learn about the java interfaces

Packages are used in Java in order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc. A Package can be defined as a grouping of related types (classes, interfaces, enumerations and annotations ) providing access protection and namespace management.

  • Preventing naming conflicts. For example there can be two classes with name Employee in two packages, college .staff.cse.Employee and college.staff.ee.Employee
  • Making searching/locating and usage of classes, interfaces, enumerations and annotations easier
  • Providing controlled access: protected and default have package level access control. A protected member is accessible by classes in the same package and its subclasses. A default member (without any access specifier) is accessible by classes in the same package only.
  • Packages can be considered as data encapsulation (or data-hiding).

Some of the existing packages in Java are −

  • java.lang − bundles the fundamental classes
  • java.io − classes for input , output functions are bundled in this package

Programmers can define their own packages to bundle group of classes/interfaces, etc. It is a good practice to group related classes implemented by you so that a programmer can easily determine that the classes, interfaces, enumerations, and annotations are related.

Since the package creates a new namespace there won’t be any name conflicts with names in other packages. Using packages, it is easier to provide access control and it is also easier to locate the related classes.

Creating a Package

While creating a package, you should choose a name for the package and include a package statement along with that name at the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you want to include in the package. The package statement should be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file. If a package statement is not used then the class, interfaces, enumerations, and annotation types will be placed in the current default package. To compile the Java programs with package statements, you have to use -d option as shown below.

javac -d Destination_folder file_name.java

Then a folder with the given package name is created in the specified destination, and the compiled class files will be placed in that folder.

Example

Let us look at an example that creates a package called animals. It is a good practice to use names of packages with lower case letters to avoid any conflicts with the names of classes and interfaces. Following package example contains interface named animals −

Now, compile this file as follows using -d option −

$javac -d . Dell.java

The files will be compiled as follows −

.\com\apple\computers\Dell.class
.\com\apple\computers\Ups.class

You can import all the classes or interfaces defined in \com\apple\computers\ as follows −

import com.apple.computers.*;

Like the .java source files, the compiled .class files should be in a series of directories that reflect the package name. However, the path to the .class files does not have to be the same as the path to the .java source files. You can arrange your source and class directories separately, as −

<path-one>\sources\com\apple\computers\Dell.java

<path-two>\classes\com\apple\computers\Dell.class

By doing this, it is possible to give access to the classes directory to other programmers without revealing your sources. You also need to manage source and class files in this manner so that the compiler and the Java Virtual Machine (JVM) can find all the types your program uses.

The full path to the classes directory, <path-two>\classes, is called the class path, and is set with the CLASSPATH system variable. Both the compiler and the JVM construct the path to your .class files by adding the package name to the class path.

Say <path-two>\classes is the class path, and the package name is com.apple.computers, then the compiler and JVM will look for .class files in <path-two>\classes\com\apple\computers.

A class path may include several paths. Multiple paths should be separated by a semicolon (Windows) or colon (Unix). By default, the compiler and the JVM search the current directory and the JAR file containing the Java platform classes so that these directories are automatically in the class path.

Set CLASSPATH System Variable

To display the current CLASSPATH variable, use the following commands in Windows and UNIX (Bourne shell) −

  • In Windows → C:\> set CLASSPATH
  • In UNIX → % echo $CLASSPATH

To delete the current contents of the CLASSPATH variable, use −

  • In Windows → C:\> set CLASSPATH =
  • In UNIX → % unset CLASSPATH; export CLASSPATH

To set the CLASSPATH variable −

  • In Windows → set CLASSPATH = C:\users\jack\java\classes.
  • In UNIX → % CLASSPATH = /home/jack/java/classes; export CLASSPATH.
packages

Built-in Packages
These packages consist of a large number of classes which are a part of Java API.Some of the commonly used built-in packages are:
1) java.lang: Contains language support classes(e.g classed which defines primitive data types, math operations). This package is automatically imported.
2)  java.io: Contains classed for supporting input / output operations.
3)  java.util: Contains utility classes which implement data structures like Linked List, Dictionary and support ; for Date / Time operations.
4)  java.applet: Contains classes for creating Applets.
5)  java.awt: Contain classes for implementing the components for graphical user interfaces (like button , ;menus etc).
6)  java.net: Contain classes for supporting networking operations.

User-defined packages
These are the packages that are defined by the user. First we create a directory myPackage (name should be same as the name of the package). Then create the MyClass inside the directory with the first statement being the package names.

// Name of the package must be same as the directory
// under which this file is saved
package myPackage;

public class MyClass
{
    public void getNames(String s)
    {        
        System.out.println(s);        
    }
}

Now we can use the MyClass class in our program.

/* import 'MyClass' class from 'names' myPackage */
import myPackage.MyClass;

public class PrintName 
{
   public static void main(String args[]) 
   {       
      // Initializing the String variable 
      // with a value 
      String name = "GeeksforGeeks";
      
      // Creating an instance of class MyClass in 
      // the package.
      MyClass obj = new MyClass();
      
      obj.getNames(name);
   }
}

Note : MyClass.java must be saved inside the myPackage directory since it is a part of the package.

Using Static Import

Static import is a feature introduced in Java programming language ( versions 5 and above ) that allows members ( fields and methods ) defined in a class as public static to be used in Java code without specifying the class in which the field is defined.
Following program demonstrates static import :

// Note static keyword after import.import static java.lang.System.*; class StaticImportDemo{public static void main(String args[]){      // We don't need to use 'System.out' // as imported using static.out.println("GeeksforGeeks");}}

Output:

 GeeksforGeeks

Handling name conflicts

The only time we need to pay attention to packages is when we have a name conflict . For example both, java.util and java.sql packages have a class named Date. So if we import both packages in program as follows:

import java.util.*;
import java.sql.*;

//And then use Date class, then we will get a compile-time error :

Date today ; //ERROR-- java.util.Date or java.sql.Date?

The compiler will not be able to figure out which Date class do we want. This problem can be solved by using a specific import statement:

import java.util.Date;
import java.sql.*;

If we need both Date classes then, we need to use a full package name every time we declare a new object of that class.
For Example:

java.util.Date deadLine = new java.util.Date();
java.sql.Date today = new java.sql.Date();

Directory structure

The package name is closely associated with the directory structure used to store the classes. The classes (and other entities) belonging to a specific package are stored together in the same directory. Furthermore, they are stored in a sub-directory structure specified by its package name. For example, the class Circle of package com.zzz.project1.subproject2 is stored as “$BASE_DIR\com\zzz\project1\subproject2\Circle.class”, where $BASE_DIR denotes the base directory of the package. Clearly, the “dot” in the package name corresponds to a sub-directory of the file system.

The base directory ($BASE_DIR) could be located anywhere in the file system. Hence, the Java compiler and runtime must be informed about the location of the $BASE_DIR so as to locate the classes. This is accomplished by an environment variable called CLASSPATH. CLASSPATH is similar to another environment variable PATH, which is used by the command shell to search for the executable programs.

Setting CLASSPATH:
CLASSPATH can be set by any of the following ways:

  • CLASSPATH can be set permanently in the environment: In Windows, choose control panel ? System ? Advanced ? Environment Variables ? choose “System Variables” (for all the users) or “User Variables” (only the currently login user) ? choose “Edit” (if CLASSPATH already exists) or “New” ? Enter “CLASSPATH” as the variable name ? Enter the required directories and JAR files (separated by semicolons) as the value (e.g., “.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar”). Take note that you need to include the current working directory (denoted by ‘.’) in the CLASSPATH.
    To check the current setting of the CLASSPATH, issue the following command:> SET CLASSPATH
  • CLASSPATH can be set temporarily for that particular CMD shell session by issuing the following command:> SET CLASSPATH=.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar
  • Instead of using the CLASSPATH environment variable, you can also use the command-line option -classpath or -cp of the javac and java commands, for example,> java –classpath c:\javaproject\classes com.abc.project1.subproject2.MyClass3
  • Every class is part of some package.
  • If no package is specified, the classes in the file goes into a special unnamed package (the same unnamed package for all files).
  • All classes/interfaces in a file are part of the same package. Multiple files can specify the same package name.
  • If package name is specified, the file must be in a subdirectory called name (i.e., the directory name must match the package name).
  • We can access public classes in another (named) package using: package-name.class-name

Differentiation of Packages in Java
Show Buttons
Hide Buttons