1
0

Packages and Interfaces in Java

All classes in Java belong to some package. When no package statement is specified, the default (or global) package is used. Furthermore, the default package has no name, which makes the default package transparent. This is why you haven’t had to worry about packages before now. While the default package is fine for short, sample programs, it is inadequate for real applications. Most of the time, you will define one or more packages for your code.

A package is a mechanism for organizing a group of related files in the same directory. In a computer system, we organize files into different directories according to their functionality, usability, and category. An example of a package is the Java package of SUN Java as shown below:

Package Name Description
java.lang Contains a large number of general-purpose classes
java.io Contains the I/O classes
java.net Contains those classes that support networking
java.applet Contains classes for creating applets
java.awt Contains classes that support the Abstract Window Toolkit
Java.util Contains some abstract datatypes and interfaces
Java.swing Contains second-generation graphics elements

In Java, a package is a group of related types classes, and interfaces that provide access protection and name space management to use those classes and interfaces. Apart from these, Java also supports special kinds of classes and interfaces known as Enumerations and Annotation, respectively.

Packaging is used to organize classes that belong to the same files or provide similar functionality. Apart from this, it also helps the programmer to avoid class name collision when we use the same class name as available in another package. For example, the Date class of java.awt package is used to access the methods of the class. But, if we have a class name “Date” (user-defined) in our program, its name would clash with the Date class of java.util package. To avoid this problem, we can use a Package through which the “Date” class can be put up into another package like india.mycompany.Date without collision with anyone.

Generally, classes in one package (or directory) have different functionality from another package. For example, classes in the java.io package manage the Input/Output streams to read and write data from and to files, while classes in the java.net package give us the way to deal with the network operations.

Features of Java Packages #

  • The protected members of the classes can be accessed by each class in the same package.
  • It resolves the naming collision for the types it contains.
  • A package may contain the following types.
    • Interfaces
    • Classes
    • Enumerated types
    • Annotations

Naming convention and Rules for using the packages

  1. Package names are written in all lowercase to avoid conflict with the names of classes or interfaces.
  2. The directory name must be the same as the name of the package that is created using the “package” keyword in the source file.
  3. Before running a program, the classpath must be picked up till the main directory (or package) that is used in the program.
  4. If we are not including any package in our Java source file then the source file automatically goes to the default package.
  5. In general, we start a package name begins with the order from top to bottom level.
  6. In the case of the Internet domain, the name of the domain is treated in reverse (prefix) order.

Creating Package #

To create your own package for organizing classes use the package keyword. You can decide the name of the package according to naming rules. The package statement must be the first statement in the Java source file after the comments if any. The common syntax of package statements is:

package package_name;

For example, the following statement creates a package called Project1.

package Project1;

Java uses the file system to manage packages, with each package stored in its own directory. For example, the .class files for any classes you declare to be part of Project1 must be stored in a directory called Project1. Like the rest of Java, package names are case-sensitive. This means that the directory in which a package is stored must be precisely the same as the package name. If you have trouble trying the examples in this module, remember to check your package and directory names carefully.

More than one file can include the same package statement. The package statement simply specifies to which package the classes defined in a file belong. It does not exclude other classes in other files from being part of that same package. Most real-world packages are spread across many files.

You can create a hierarchy of packages. To do so, simply separate each package name from the one above it by use of a period. The general form of a multileveled package statement is shown here:

package package1.package2.package3...packageN;

Of course, you must create directories that support the package hierarchy that you create. For example,

package P1.P2.P3;

For example suppose we want to keep the classes Rectangle, Circle, and Semicircle in the figure’s package. Then the file containing the definition of these classes must have code like:

package figures;
public class Circle
{
    ...
}
package figures;
public class Rectangle
{
    ...
}

The directory that contains these classes must have the same name as that of the package. So, you must save these files in the figures directory and compile them to generate the .class files. If you save the Java source file in the parent directory of the figures subdirectory then you should use the -d option with the javac command to place the .class file in the proper directory. For example, consider the directory structure c:\>program\figures. Suppose you save the Java source file in the program directory and you want the .class file to be placed in the figures directory. Then use the following command:

C:\program>javac -d figures Circle.java

This command will place Circle.class file in the ‘figures’ subdirectory.

Adding Classes

To add classes to the existing package just follow the following simple steps:

  • Create your program source file with the package statement as the first statement.
  • Save this file in the directory having the same name as that of the package name.
  • The name of the file must be the same as that of the public class in the file.
  • Compile the source code file to create a .class file in the same directory.

For example, suppose we have a package named ‘figure’. We want to add a class Square to it. First of all, write the source code of the Square class as shown below.

Program to demonstrate the creation of a package

package figure:     // package declaration
public class Square
{
    float side;
    float area;
    Square();
    {
        side = 0.0f;
    }
    Square(float a, float b)
    {
        side = a;
    }
    public void calArea()
    {
        area = side*side;
    }
    public void dispArea()
    {
        System.out.println("Area of Square = " + area);
    }
}

Save this file as Square.java in the ‘figure’ directory. Compile the file to create a Square.class file in the same directory.

It should be kept in mind that if a file contains more than one class definition then only one of them can be public. The name of the file must match the public class name.

Using Packages #

We have discussed many examples in which predefined packages of Java are used using the import statement. To access classes defined in a package we have to use an import statement. The general syntax of this statement is :

import package1.package2....packageN.*;

OR

Import package1.package2....packageN.Classname;

If we use the first form of import statement then all the public classes defined in packagesN are accessible to the program in hand. So if we want to use more than one class from the same package the first form of import statement is used.

If we use the second form of import statement then the specified class from the packageN can be used in the current program. This version is more restrictive.

For example:

import java.io.*;       //use all classes of io package
import java.io.DataInputStream; //use DataInputStream class from io package.

Hiding Classes

Normally all public classes from a package are accessible in a program that imports the package. If we want to hide some classes then these must be defined as private classes in the package. The import statement can not access private classes defined within the package. Hence these classes are treated as hidden from the others packages.

How to Set the Class Path:

The classpath is a user-defined environment variable that is used by Java to determine where predefined classes are located. It tells the Java tools and applications where to find user-defined classes. The syntax to set the classpath is shown as:

C:> set CLASSPATH=%classpath%;classpath1;classpath2......

You can set multiple path entries that are separated by semi-colons.

To make this thing more understandable, let’s put the “HelloWorld” class along with its package “mypackage” under the “C:\mainpackage” directory. Thus the directory structure for this package is shown as:

Now we have changed the location of the package from C:\mypackage\HelloWorld.java to C:\mainpackage\mypackage\HelloWorld.java. Then the CLASSPATH needs to be changed to point to the new location of the package mypackage accordingly shown as:

set CLASSPATH = .;C:\mainpackage\mypackage

Although in such conditions, Java will look for Java classes from the current directory instead f the “C:\mainpackage” directory.

packages and interfaces in java

Visibility Controls #

By specifying member accessibility modifiers, a class can control what information is accessible to clients (i.e. other classes). These modifiers help a class to provide restrictive access of its members to the other classes. If we do not specify any of the access control with class or method then default access control is used. The default access control is friendly access which means classes and members with friendly access are available to classes in the same package. To restrict access we can use protected or private access control and widen the scope we can use public access control.

Accessibility of members can be one of the following:

  • public
  • protected
  • private
  • default (also called package accessibility)

A member has package or default accessibility when no accessibility modifier is specified. A member accessibility modifier only has meaning if a class (or one of its subclass) is accessible to the client (Other classes). Also, note that only one accessibility modifier can be specified for a member.

Access protection in packages:

Access protection Description
No modifier (default) The classes and members specified in the same package are accessible to all the classes inside the same package.
public The classes, methods, and member variables under this specifier can be accessed from anywhere.
protected The classes, methods, and member variables under this modifier are accessible by all subclasses, and accessible by code in the same package.
private The methods and member variables are accessible only inside the class.

Access to the fields in Java at a Glance:

Access By public protected default private
The class itself Yes Yes Yes Yes
A subclass in the same package Yes Yes Yes No
Non sub-class in the same package Yes Yes Yes No
A subclass in another package Yes Yes No No
Non-subclass in another package Yes No No No

 

Interfaces #

Some object-oriented programming languages, such as C++, allow a class to extend two or more super classes. This is called multiple inheritance. In the illustration below, for example, class D is shown as having both class A and class B as direct super classes, while class F has three direct super classes.

Such multiple inheritance is not allowed in Java. The designers of Java wanted to keep the language reasonably simple and felt that the benefits of multiple inheritance were not worth the cost of increased complexity. However, Java does have a feature that can be used to accomplish many of the same goals as multiple inheritance i.e interfaces.

multiple inheritance (not allowed in java)

We’ve encountered the term “interface” before, in connection with subroutines and methods (method interface). The interface of a subroutine consists of the name of the subroutine, its return type, and the number and types of its parameters. This is the information you need to know if you want to call the subroutine. A subroutine also has an implementation: the block of code which defines it and which is executed when the subroutine is called.

In Java, the interface is a reserved word with additional, technical meaning. In Java programming language, the interface is nothing but the collection of methods with method declarations and final variables (variables with static and final declarations). All the methods in an interface are “public and abstract” by default. Since interfaces are abstract in nature so they can not be directly instantiated. To define the methods of an interface the keyword “implements” is used. Interfaces are similar to abstract classes but the major difference between these two is that interfaces have all the methods abstract while in case of abstract classes must have at least one abstract method. The interface combines the two functionality (template and multiple inheritance) of the C++ language into one (in itself).

To make the concept clear let us take an example program. Suppose we want to calculate the area of the circle. Here the circle is a kind of shape and uses a constant value i.e. pie. So we can have an interface named Shape that can be implemented in the class Circle.

Program to calculate the area of circle using interface

public interface Shape  // Save this as Shape.java and Compile
{
    final static double pie = 3.142;
    public void calArea();
}
class Circle implements Shape   // Save as Circle.java and Compile
{
    float rad;
    float area;
    Circle()
    {
        rad = 0.0f;
    }
    Circle(float r)
    {
        rad = r;
    }
    public void calArea()
    {
        area = (float)pie*rad*rad;
    }
    void dispArea()
    {
        System.out.println("Area of Circle = " + area);
    }
}
public class InterfaceMain  // Save as InterfaceMain.java Compile and Run
{
    public static void main(String args[])
    {
        Circle c = new Circle(5.5f);
        c.calArea();
        c.dispArea();
    }
}

The output produced by this program is shown here:

Area of Circle = 95.0455

Creating and Using Interfaces

The syntax for interface creation is:

<visibility mode> interface <interfaceName>
{
    static final variable declaration
    abstract method declaration
}

The variables in the interface are declared as static and final and all the methods declared in the interface are abstract and need to be implemented in the class that uses the interface.

Here is an example of a very simple Java interface:

public interface Shape
{
    final static double pie = 3.142;
    public void calArea();
}

This looks much like a class definition, except that the implementation of the calArea() method is omitted. A class that implements the interface Shape must provide an implementation for this method. Of course, the class can also include other methods and variables. For example,

public class Circle implements Shape
{
    float rad;
    float area;
    Circle()
    {
        rad = 0.0f;
    }
    Circle(float r)
    {
        rad = r;
    }
    public void calArea()   // implements of calArea() method
    {
        area = (float)pie*rad*rad;
    }
    void dispArea()
    {
        System.out.println("Area of Circle = " + area);
    }
}

Note that to implement an interface, a class must do more than simply provide an implementation for each method in the interface; it must also state that it implements the interface, using the reserved word implements as in this example: “public class Circle implements Shape”. Any class that implements the Shape interface defines a calArea() instance method. Any object created from such a class includes a calArea() method. We say that an object implements an interface if it belongs to a class that implements the interface. For example, any object of type Circle implements the Shape interface.

While a class can extend only one other class, it can implement any number of interfaces. In fact, a class can. both extend one other class and implement one or more interfaces. So, we can have things like

class semiCircle extends Circle implements Shape, Fillable
{
    ......
}

The point of all this is that, although interfaces are not classes, they are something very similar. An interface is very much like an abstract class, that is, a class that can never be used for constructing objects, but can be used as a basis for making subclasses. The subroutines in an interface are abstract methods, which must be implemented in any concrete class that implements the interface. And as with abstract classes, even though you can’t construct an object from an interface, you can declare a variable whose type is given by the interface. For example, if Shape is an interface, and if Rectangle and Circle are classes that implement Shape, then you could say:

Shape figure;               // Declare a variable of type Shape. It can 
                            // refer to any object that implements the 
                            // Shape interface.
figure = new Rectangle();   // figure now refers to an object of class Rectangle
figure.calArea();           // calls calArea() method from class Rectangle
figure = new Circle();      // Now, figure refers to an object of class Circle
figure.calArea();           // calls calArea() method from class Circle

A variable of type Shape can refer to any object of any class that implements the Shape interface. A statement like figure.cal Area(), above, is legal because the figure is of type Shape, and any Shape object has a calArea() method. So, whatever object figure refers to, that object must have a calArea() method.

Note that a type is something that can be used to declare variables. A type can also be used to specify the type of a parameter in a subroutine or the return type of a function. In Java, a type can be either a class, an interface, or one of the eight built-in primitive types. These are the only possibilities. Of these, however, only classes can be used to construct new objects.

You are not likely to need to write your own interfaces until you get to the point of writing fairly complex programs. However, there are a few interfaces that are used in important ways in Java’s standard packages.

Program to illustrate the use of Interface to implement multiple Inheritance.

public interface Shape      // save as Shape.java and compile
{
    final static double pie = 3.142;
    public void calArea();
    public void dispArea();
}

// ------------------------------------------------------------

class Circle implements Shape       // Save as Interface2Main.java
{
    float rad;
    float area;
    Circle()
    {
        rad = 0.0f;
    }
    Circle(float r)
    {
        rad = r;
    }
    public void calArea()
    {
        area = (float)pie*rad*rad;
    }
    public void dispArea()
    {
        System.out.println("Area of Circle = " +  area);
    }
}
class SemiCircle extends Circle implements Shape
{
    SemiCircle()
    {
        super();
    }
    SemiCircle(float r)
    {
        super(r);
    }
    public void calArea()
    {
        area = (float)pie*rad*rad*0.5f;
    }
    public void dispArea()
    {
        System.out.println("Area of Semi-circle = " + area);
    }
}
class Interface2Main
{
    public static void main(String args[])
    {
        Shape figure;
        Circle c = new Circle(5.5f);
        SemiCircle sc = new SemiCircle(5.5f);
        figure = c;
        figure.calArea();
        figure.dispArea();
        figure = sc;
        figure.calArea();
        figure.dispArea();
    }
}

The output produced by this program is shown here:

Area of circle = 95.0455
Area of Semi-circle = 47.52275

Marker Interfaces #

In Java language, interfaces with no methods are known as marker interfaces. Marker interfaces are Serializable, Clonable, SingleThreadModel, and Event listener. Marker Interfaces are implemented by the classes or their super classes in order to add some functionality. e.g. Suppose you want to persist (save) the state of an object then you have to implement the Serializable interface otherwise the compiler will throw an error. To make more clearly understand the concept of marker interface you should go through one more example.

Suppose the interface Clonable is neither implemented by a class named Myclass nor it’s any super class, then a call to the method clone() on Myclass’s object will give an error. This means, to add this functionality one should implement the Clonable interface. While the Clonable is an empty interface but it provides important functionality.

Difference Between Interfaces and Abstract Classes #

Some important differences between Interface and abstract classes are given here

Features Interface Abstract Class
Methods An interface contains all the methods with empty implementation. An abstract class must have at least one method with empty implementation.
Variables The variables in interfaces are final and static. Abstract classes may contain both instance as well as static variables.
Multiple Inheritance In Java, multiple inheritance is achieved by using the interface (by implementing more than one interface at a time). Abstract classes do not provide this functionality.
Additional Functions If we add a method to an interface then we will have to implement this interface by any class. In Abstract classes, we can add a method with default implementation and then we can use it by extending the abstract class.

Leave a Reply