9 Packages and Interfaces

9.1 INTRODUCTION

A packing is a grouping of related types providing access protection and name space management. Note that all types refer to classes and interfaces. Many a time while working on a small project, one thing that is intended to do is to put all Java files into a single directory. It is quick, easy and harmless. However, if the small project gets bigger and the number of files keeps on increasing, putting all these files into the same directory and managing them would be a difficult task. In Java, this sort of problem can be avoided by using package.

Packages are nothing more than the way files are organized into different directories according to their functionality, usability as well as category they should belong to. A clear example of package is JDK. In JDK, all the packages that can be used in Java programs are part of the Java package, which itself contains a number of packages. In fact, there is a directory named java inside which each directory represents a package, e.g., java.lang, java.util, java.awt, java.net, etc. The notation java.lang means that inside Java package, there is a sub-package lang .

Basically, files in one directory (or package) would have different functionality from those of another directory. For example, files in java.io package do something related to I/O, but files in java.net package give one the way to deal with the network. In GUI applications, it is quite common to see a directory with a name 'ui' (user interface), which keeps files related to the presentation part of the application. On the other hand, a directory called engine, stores all files related to the core functionality of the application.

Packaging also helps avoid class name collision when the same class name is used as that of others. For example, in a class name called Vector, its name would crash with the Vector class from JDK. However, this never happens because JDK uses java.util as a package name for the Vector class (java.util. Vector). So the Vector class can be named as Vector or it can be put into another package like com.mycompany.Vector without fighting with anyone. The benefits of using the package are the ease of maintenance, organization and increase collaboration among developers. Understanding the concept of package will also help one to manage and use files stored in jar files in more efficient ways.

9.2 PACKAGE TYPES

Packages are of two types: built-in and user defined.

9.2.1 Built-in Packages

The root of all Java packages is the built-in package. Inside this package, a number of other standard packages are defined. It is not possible to discuss all of the packages because of space constraint. Some of the most commonly used packages and a brief description of each is given in Table 9.1.

Package Name Description
java.applet Provides classes necessary for the creation of applets and related operations.
java.io Provides classes for system input and output through data streams, serialization and file manipulation.
java.lang Provides classes that are default and required for fundamental Java programming. This package is default and imported to all Java programs.
java.net Provides classes necessary for implementing networking applications.
java.util Contains the collections framework and classes, date and time facilities and miscellaneous utility classes (a string tokenizer, a random-number generator and a bit array, Vector, etc.).
java.rmi The package and its sub-package provide classes for remote method invocation.
java.awt Contains all the classes essential for creating user interfaces like buttons, textboxes, panels, etc. and for painting graphics and images.
java.sql Provides the API for accessing and processing data stored source (usually relational database) in RDBMS like MS-Access, SQL Server, or Oracle using Java programming language.
java.math Provides class for performing arbitrary-precision integer arithmetic (BigInteger) and arbitrary-precision decimal arithmetic (BigDecimal). BigInteger is analogous to the primitive integer type of Java except that it provides arbitrary precision. Hence, operations on BigIntegers do not overflow or lose precision.
java.text Provides classes and interfaces for handling text, dates, numbers and messages in a manner independent of natural languages. These classes are capable of formatting date, numbers and messages; parsing, searching and sorting strings and iterating over characters, words, sentences and line breaks.
java.awt.event Provides interfaces and classes for dealing with different types of events fired by AWT components.
java.awt.image Provides classes and interfaces for creating and modifying images.
java.rmi.registry Provides a class and two interfaces for the RMI registry.
java.rmi.server Provides classes and interfaces for supporting the server side of RMI.
java.util.zip Provides classes for reading and writing the standard ZIP and GZIP file formats.

Table 9.1 Some built-in packages defined in Java

All these and other packages can be imported and classes defined within can be used. For this, import statement can be used as in other programs.

9.2.2 User-defined Packages

Built-in packages have been used in a number of Java programs. Now the focus is how to create one's own package and use it just like a built-in package.

1. How to create a package: Suppose, there is a file called Hello.java and this file needs to be put in a package named Package1. In order to create a package, a name for the package is chosen and a package statement put with that name at the top of every source file that contains the types (classes, interfaces) that are to be included in the package.

The package statement (e.g., package pack1) must 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.

So the first thing that is to be done is to specify the keyword package with the name of the package required to be used (Package1 in our case) on the top of the source file before the code that defines the real classes in the package as shown in the Hello class below.

package package1;
public class Hello
{
      public static void main(String[] args)
      {
           System.out.println("Hello world");
      }
}

The file created must be placed in a directory named Package1 and file name must be Hello. java. The first statement package package1; tells the Java compiler that the file is to be made a part of the package package1. Remember that case is significant and the directory name must match with the package name exactly.

2. Setting up the classpath and running program: This variable is used for controlling the access to a specific package. The class search path (commonly known as 'classpath') is the path where the Java runtime environment searches for the classes and other resource files. The classpath can be set using either the classpath option when calling a JDK tool (the preferred method) or by setting the CLASSPATH environment variable. In the absence of any package, it is seen that all files and classes reside in one directory and any of the files and classes can be used in other Java programs within the same directory. This is valid, as by default, CLASSPATH variable contains default current working directory in its path which is represented by a dot (.) symbol.

When the number of classes are grouped together under one package and the same package is wanted to be used in a number of Java programs, Java needs to be instructed about the location of that package. Here comes the role of CLASSPATH environment variable. It can be set in the following way:

set CLASSPATH = classpath1; classpath2

For .class files in a named package, the classpath ends with the directory that contains the 'root' package (the first package in the full package name). The multiple path entries are separated by semicolons. With the set command, it is important to omit spaces from around the equals sign (=). The default classpath is the current directory. Setting the CLASSPATH variable or using the -classpath command-line option overrides that default, so in order to include the current directory in the search path, one must include '.' in the new setting.

It can be understood in continuation of the program stated in the example above.

The package package1 is put under C (i.e., C drive). So the CLASSPATH is set in the following way:

Set CLASSPATH = .; C:;

images

Figure 9.1 Showing the CLASSPATH setting

images

Figure 9.2 Showing the CLASSPATH setting in JPS directory

images

Figure 9.3 Contents in CLASSPATH

The CLASSPATH is wetted to point to two places, '.'(dot) and C: directory. The . is used as an alias for the current directory and .. for the parent directory. In the CLASSPATH this . is included for convention reason. Java will find the class file not only from C: directory but from the current directory as well. Also, the ; (semicolon) is used to separate the directory location, in case class files are kept in many places.

When compiling the Hello class, go to the package1 directory and type the command.

C:JPSpackage1>javac Hello.java
C:JPSpackage1>

If Hello is run using java Hello, the following error message is obtained.

C:JPSpackage1>java Hello
Exception in thread "main" java.lang.NoClassDefFoundError:
Hello (wrong name: package1/Hello)

The error message occurs because the Hello class belongs to the package package1. In order to run it JVM must be told about its fully qualified class name pacakge1.Hello instead of its plain class name (Hello).

C:JPSpackage1>java package1.Hello
Hello world

Note: fully qualified class name is the name of the Java class that includes its package name.

If we do not want to setup the CLASSPATH variable we can use -classpath option while compiling the Java program in the following way:

For running the Java program without setting CLASSPATH variable again the -classpath option can be used in the following way:

This comes handy when the classpath changes frequently or just for the time being when one wants to use the classpath.

The classpath variable can also be set in the following order:

1.   Right click on My Computer and then go to properties

2.   Click on Advanced Tab and then Environment Variables

3.   Under the System Variable Frame heading, click on new and give a new name to the system variable CLASSPATH and set the value as desired

4.   Save changes by clicking on OK and come out

To make this example more understandable, the Hello class can be put to system package (package1) can be understand C:myclasses directory instead. The location of the package is just changed from C:package1Hello.java to C:myclassespackage1Hello.java. The CLASSPATH then needs to be changed to point out to the new location of the package package1 accordingly.

Thus, Java will look for java classes from the current directory and C:myclasses directory instead. The Hello can be run from anywhere as long as the package package1 is included in the CLASSPATH.

For example, look at the following program:

C:>set CLASSPATH=.;C:;
C:>set CLASSPATH
CLASSPATH=.;C:;
C:>cd package1
C:package1>java package1.Hello
Hello world
C:package1>cd..
C:>java package1.Hello
Hello world

3. Importing built-in packages: The method to import built-in packages using import statements has been seen in the earlier programs. The import statement is used for importing classes and related packages into Java programs. When creating one's own package and importing other packages also, the import statement must come after the package statement. The general syntax of import statement is as follows:

The arguments inside [] are optional and arguments within () are compulsory. When you import the whole package in the following way:

it means that you are importing all classes, constants, interfaces, etc. from the package java.io. In case, you just need one class from this package in your program, the whole of the package will be imported to your Java program, which may sometimes increase compilation time. This type of import form is known as implicit import statement as all classes are implicitly imported to the Java program. Moreover, in case the class name is explicitly mentioned within the package, the import statement becomes an explicit import statement as given below.

import java.io.DataInputStream;    //explicit import

Note that there is no static linking in terms of Java and so importing packages implicitly or explicitly does not affect the size of the class and execution of the program.

The standard Java package is Java in which all of the commonly used classes and other package are stored.

4. Importing user-defined package: Create a new package demo_pack by creating a new directory by the name demo_pack. Assume we are in C: drive. Now move to directory demo_pack and create a new file in it by the name demo1.java in the following way:

Type the following program into it.

package demo_pack;
public class demo1
{
   public void show()
   {
          System.out.println("Welcome to Package");
   }
   public int sum(int x, int y)
   {
          return x + y;
   }
}

In the program, a file demo1 is created, inside which there are two public functions, show and sum, which are simple to understand. Now, compile the file which will create demo1.class file.

In order to import this package and use the class demo1 in the program, create a new file, e.g., main.java and type the following code into it.

import demo_pack.demo1;
class main
{
   public static void main(String[] args)
   {
          demo1 d = new demo1();
          d.show();
          int s = d.sum(20, 40);
          System.out.println("Sum = " + s);
   }
}

Before compiling the program, set the CLASSPATH and if not set, then set CLASSPATH =.;C:;

Now, compile and run the program. The output will be as given below.

C:demo_pack>javac main.java
C:demo_pack>java main
Welcome to Package
Sum = 60

Hence, the class demo1 is accessed and used from package demo_pack.

One more package mypack in the same drive (C:) and a new file demo1.java will be created now .

package mypack;
public class demo1{
   public long fact(int num)
   {
          if (num <= 1)
                   return 1;
          else
          {
                   long f = 1;
                   for (int i = 1; i <= num; i++)
                   f = f * i;
                   return f;
          }
   }
   public int max(int x, int y)
   {
          return x > y ? x : y;
   }
}

Compile the file and get the class file.

Note that the class name in both the packages is demo1. In a program when both the packages, demo_ pack and mypack, are imported and demo1 class is to be used from both the packages, how can both the classes in the same program can be distinguished? The solution is that the class name has to be fully qualified using package name as demo_pack.demo1 and mypack.demo1. See the program given below.

import demo_pack.*;
import mypack.*;
class JPS
{
   public static void main(String[] args)
   {
          demo_pack.demo1 d1 = new demo_pack.demo1();
          mypack.demo1 d2 = new mypack.demo1();
          int s = d1.sum(10, 20);
          System.out.println("Sum =" + s);
          long f = d2.fact(8);
          System.out.println("Factorial of 8 is " + f);
          int m = d2.max(10, 20);
          System.out.println("Max=" + m);
   }
}
OUTPUT:
Sum =30
Factorial of 8 is 40320
Max=20

As a final example, the package for reading different types of data is created from the console and displayed back using own methods. This is stored under the package MYIO. The package consists of just one Java source file name MYINOUT.java

Compile the file and set the class path appropriately. All the methods from this class can be used now which will prove quite helpful in writing programs. This package will also be used in various other programs which will be written in this and the next chapters. The class defines six public static methods for reading integer, float, double, long, character and String data types. It also defines two public static methods for displaying string: show and showln which are equivalent to System. out.println and System.out.print method, respectively. All the methods are static and so they can be used in the Java program by importing package MYIO and using as MYINOUT.method_name. Go through the following code:

/*PACKAGE MYIO DEVELOPED FOR BASIC INPUT OUTPUT */
package MYIO;
import java.io.*;
public class MYINOUT
{
   static DataInputStream input;
   public static void showln(String str)
   {
          System.out.println(str);
   }
   public static void show(String str)
   {
          System.out.print(str);
   }
   public static int int_val()
   {
          int temp = -1;
          try
          {
                 input = new DataInputStream(System.in);
                 temp = Integer.parseInt(Input.readLine());
          }
                 catch (IOException E)
          {
                 System.out.println("Error:" + E);
          }
                 return temp;
   }
   public static float float_val()
   {
          float temp = 0.0f;
          try
          {
                 input = new DataInputStream(System.in);
                 temp=Float.valueOf(input.readLine()).
                              floatValue();
                 }
                 catch (IOException E)
          {
                 System.out.println("Error:" + E);
          }
          return temp;
   }
   public static double double_val()
   {
          double temp = 0;
          try
          {
                 input = new DataInputStream(System.in);
                 temp  = Double.valueOf(input.readLine()).
                                      doubleValue();
          }
          catch (IOException E)
          {
                 System.out.println("Error:" + E);
          }
                 return temp;
   }
   public static long long_val()
   {
                 long temp = -1;
                 try
                 {
                        input = new DataInputStream(System.in);
                        temp = Long.parseLong(input.readLine());
                 }
                 catch (IOException E)
                 {
                        System.out.println("Error: " + E);
                 }
                        return temp;
   }
   public static String str_val()
   {
          String str = null;
          try
          {
                 input = new DataInputStream(System.in);
                 str = input.readLine();
          }
          catch (IOException E)
          {
                 System.out.println("Error:" + E);
          }
          return str;
   }
   public static char char_val()
   {
          char ch = ' ';
          try
          {
                 input = new DataInputStream(System.in);
                 ch = (char)input.read();
          }
          catch (IOException E)
          {
                 System.out.println("Error:" + E);
          }
          return ch;
   }
}

5. Controlling access using packages: It is understood that a class is the smallest unit of providing encapsulation and abstraction. Inside the class, visibility modifier like private, public and protected, etc., can be used for controlling the access of data to other classes. This notion of access control can be extended to the package also. In package, when a file is created by the name such as myfile.java then in the file there can be only one public class by the name myfile. If you can create a number of .java file and can make one class to use other classes within the same package without extending them.

As package is a collection of classes and interfaces; some methods in the package can be made as public and some as private or protected, etc. When this type of access protection is provided for classes inside the packages then depending on what type of access specifier is set for the class or method and where they are being used, Java provides four levels of visibility for class and its data members, which are as follows:

(a) Subclass in same package : For example, in our earlier discussion we had demo1 class in mypack package. Now, if we create a new file demo2.java and inside it, demo2 class extends demo1 class then it will be an example of the category shown below.

//file demo2.java
  package mypack;
  public class demo2 extends demo1
  {
     private String name;
     void setName(String s)
     {
            name = s;
     }
     String getName()
     {
            return name;
     }
  }

In this category, except private members of demo1, class all other members will be available for use in demo2 class.

(b) Non-subclasses in same package: As this category includes classes from within the same packages in other classes without inheriting them, it is called non-subclasses. This category is similar to the first category as whether or not it extends classes from within the same package, we are able to use them in other classes except private data members.

(c) Subclasses in different packages: Assume that we are in a directory C:JPSch9 and want to inherit the classes defined within package mypack. It means that it is an example of the third category of visibility using packages. Look at the example of the program given below.

import java mypack.demo2;
class use extends demo2
{
}
class JPS1
{
   public static void main(String [] args)
   {
          use obj = new use();
          obj.setName("Hari");
          System.out.println(obj.getName());
          System.out.println(obj.max(10,40));
   }
}
OUTPUT:
Hari
40

In case use class, extend class demo2 and uses methods of class demo2 from an object class used in the main function. This works fine and the output produced is shown in the program above. In this category, only protected and public data members and methods can be accessed within the use class, while Private and default access is not allowed. Look at one more example where we create a new file demo3.java in the mypack package below.

package mypack;
public class demo3
{
   public void pub_show()
   {
          System.out.println("public show");
   }
   private void pri_show()
   {
          System.out.println("private show");
   }
   protected void pro_show()
   {
          System.out.println("protected show");
   }
   void def_show()
   {
          System.out.println("default show");
   }
}

In the class, there are four functions each of which displays a string. Each function is tagged as private, protected and public. The fourth function is default without any access specified. Compile the file so that you get .class file. Now, create a new file in C:JPSch9 (assume) and extend the class demo3 in the following way:

import mypack.demo3;
class use1 extends demo3
{
   void useshow()
   {
          pro_show();
          }
}
class JPS2
{
   public static void main(String[] args)
   {
          use1 obj = new use1();
          obj.useshow();
   }
}
OUTPUT:
C:JPSch9>java JPS2
protected show

In the program, demo3 is extended into class use1. As mentioned above, only public and protected members will be allowed. But note that these protected members would not be allowed outside the use1 class. This being the reason, a function useshow is created and in this method, pro_show function is called which is protected in demo3 class. If the program is run as given below, it will result in compilation error.

import mypack.demo3;
class use extends demo3
{
}
class JPS3
{
   public static void main(String[] args)
   {
          use obj = new use();
          obj.pro_show();
   }
}
OUTPUT
C:JPSch9>javac JPS3.java
JPS3.java:10: pro_show() has protected access in mypack.demo3
          obj.pro_show();
             ^
1 error

(d) Non-subclasses in other packages: This includes classes which are neither in the same package nor are the derived class of any of the classes defined within the package but yet wants to access classes from the package. In order to understand this, the above class is used into some other package. For this purpose, one can assume to be in C:JPSch9 package and write the program in the following way:

import mypack.demo3;
class JPS4
{
   public static void main(String[] args)
   {
          demo3 temp = new demo3();
          //temp.def_show();
          temp.pub_show();
          //temp.pri_show();
          //temp_pro_show();
   }
}
OUTPUT:
C:JPSch9>java JPS4
public show

In this category, only the public members of the class can be accessed from the package and all commented lines will generate errors.

A complete access protection table using packages is shown in Table 9.2.

images

Table 9.2 Access protection table for packages

9.3 INTERFACES

Methods form the interface of the object with the outside world. The buttons on the front of a television set, for example, are the interface between the viewer and the electrical writing on the other side of its plastic casing. You press the 'power' button to turn the television on and off. The operating system like Unix, Linux and Windows form an interface between the PC and the user.

In Java, an interface is similar to an abstract class wherein its members are not implemented. In interfaces, none of the methods are implemented. There is no code associated with an interface. In its most common form, an interface is a group of related methods with empty bodies and constants. An interface is a specification or contract for a set of methods which a class that implements the interface must conform to, in terms of the type signature of the methods. The class that implements the interface provides an implementation for each method, just as with an abstract method in an abstract class.

So, an interface can be considered as an abstract class with all abstract methods. The interface itself can have either public, package, private or protected access defined. All methods declared in an interface are implicitly abstract and implicitly public . It is not necessary and in fact considered redundant to declare a method in an interface to be an abstract. Data can be defined in an interface, but it does not happen usually. If there are data fields defined in an interface, they are implicitly defined as public, static and final.

In other words, any data defined in an interface are treated as public constants. Note that a class and an interface in the same package cannot share the same name. Interface is the only mechanism which allows implementing multiple inheritances in Java.

9.3.1 Interface Declaration

An interface is declared by using the keyword interface followed by the interface name. For example:

interface demo
{
   void fun();
}

Before interface keyword, you can also specify access specifiers such as public, private, protected, etc. All methods declared inside an interface are by default abstract. The general syntax of creating an interface is as follows:

access_specfier interface interface_name
{
   return_type method_name1(parameters);
   ........... ;
   ........... ;
   ……………………….. ;
   data_type final constant_name = value;
   ........... ;
   …………………………… ;
}

All the variables declared inside an interface are by default considered as final and static. They can only be used by the class implementing the interface. The implementing class cannot change the constants. The default access specifier is public for an interface and the same applies to all its members.

9.3.2 Interface Implementation

An interface that is declared can be used by the class. The syntax is as shown below.

class class_name implements interface_name
{
   //implementing interface's method;
   //own method and data;
}

An interface declaration is nothing more than a specification to which some classes that wish to implement the interface must conform to in its implementation. This means that a class that implements the interface must define implementations for each of the interface methods.

To make use of an interface, it has to be inherited by some class. An interface can also inherit the interface for extending purpose. For inheriting an interface, either to a class or an interface, 'implements' keyword is used. Look at the example below.

All methods of interfaces when implementing in the class must be declared public otherwise, it may result in compilation error.

Some other class might provide different implementation of method fun as given below.

class temp implements demo
{
   public void fun()
   {
         System.out.println("Using interface demo");
   }
}

Look at another example below.

interface Bicycle
{
   void changeGear(int newValue);
   void speedUp(int increment);
   void applyBreakes(int decrement);
}

In order to implement this interface, the name of the class would change (to HEROBicycle, for example) and the keyword implements would be used in the class declaration as given below.

class HEROBicycle implements Bicycle
{
   //implementation of methods of interface;
}

Interfaces form a contract between the class and the outside world and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all the methods defined by that interface must appear in its source code before the class will compile successfully.

The main use of interface is that one can define some codes in a very general way with a guarantee that by only using the methods defined in the interface, that all objects which implement the interface will have defined implementations for all the methods.

9.3.3 Programming Examples

The following program makes use of the interface with class.

/*PROG 9.1 DEMO OF INTERFACE VER 1*/
interface i_demo
{
   void show();
}
class first implements i_demo
{
   public void show()
   {
          System.out.println("
show of first");
   }
}
class second implements i_demo
{
   public void show()
   {
          System.out.println("
show of second");
   }
}
class JPS5
{
   public static void main(String[] args)
   {
          i_demo ref = new first();
          ref.show();
          ref = new second();
          ref.show();
   }
}

OUTPUT:

show of first
show of second

Explanation: The interface i_demo has just one method show(). The first and second class implements this interface and provides the implementation for the method show(). In the main a reference of i_demo is created. First, it gets the reference of an object of the class first and then calls the show() method. The show of class first is called. Later on, it gets the reference of an object of the class second and calls the method show() of the class second. Note that as explained before, the methods can also be called by creating reference of the class first and second using abstract classes as given below.

first f = new first();
f.show();

and

second s = new second();
s.show();
/*PROG 9.2 DEMO OF INTERFACE VER 2 */
interface i_demo
{
   void show();
}
class first implements i_demo
{
   public void show()
   {
          System.out.println("Show of first");
   }
   void display()
   {
          System.out.println("display of first");
   }
}
class JPS6
{
   public static void main(String[]args)
   {
          i_demo ref=new first();
          ref.show();
          ref.display();
   }
}

OUTPUT:

Compilation Error:
C:JPSch9>javac JPS6.java
JPS6.java:23: cannot find symbol
symbol : method display()
location: interface i_demo
                 ref.display();
                 ^

1 error

Explanation: A reference of interface can only call the methods declared in it and implemented by the implementing class. The display is not a part of the interface rather a part of the class first. Therefore, it can only be called by an object reference of the class first. Hence, the code gives error. In order to rectify, the code can be changed as follows:

first f = new first();
f.show();
f.display();
/*PROG 9.3 FINDING COLORS OF VEGETABLE AND WHERE THEY GROW */
interface Vegetable
{
   void color();
   void wh_grow();
}
class Spinach implements Vegetable
{
   public void color()
   {
          System.out.println("
Color of spinach is green");
   }
   public void wh_grow()
   {
          System.out.println("Spinach grows above ground");
   }
};
class Potato implements Vegetable
{
   public void color()
   {
          System.out.println("
Color of Potato is browny
                                           white");
   }
   public void wh_grow()
   {
          System.out.println("Potato grows under ground");
   }
};
class Onion implements Vegetable
{
   public void color()
   {
          System.out.println("
Color of Onion is red");
   }
   public void wh_grow()
   {
          System.out.println("Onion grows under ground");
   }
};
class Tomato implements Vegetable
{
   public void color()
   {
          System.out.println("
Color of Tomato is red");
   }
   public void wh_grow()
   {
          System.out.println("Tomato grows above ground");
   }
};
class JPS7
{
   public static void main(String []args)
   {
          Vegetable ptr[]=new Vegetable[4];
          ptr[0] = new Spinach();
          ptr[1] = new Potato();
          ptr[2] = new Onion();
          ptr[3] = new Tomato();
          for(int i=0;i<4;i++)
          {
                   ptr[i].color();
                   ptr[i].wh_grow();
          }
   }
}
OUTPUT:

Color of spinach is green
Spinach grows above ground

Color of Potato is browny white
Potato grows under ground

Color of Onion is red
Onion grows under ground

Color of Tomato is red
Tomato grows above ground

Explanation: The interface 'Vegetable' declares two functions. The functions color is used for finding the colour of the vegetable and wh_grow for finding where the vegetable grows: underground or above ground. Any class that inherits the vegetable class has to redefine these functions and tell what the colour of vegetable is and where it grows. The interface 'Vegetable' is implemented, for example, by four different classes: spinach, potato, onion and tomato. Each class provides the implementation of both the functions. In the main, an array of reference ptr of interface Vegetable type is created. In each reference of this array, a dynamically created object of various derived classes is created which is shown below.

ptr[0] = new Spinach();
ptr[1] = new Potato();
ptr[2] = new Onion();
ptr[3] = new Tomato();

In the for loop, when functions color and wh_grow are called using this reference array ptr, respective functions, color and wh_grow, of each class are called.

/*PROG 9.4 CHECKING WHETHER SWEET CONTAINS MAWA AS ITS MAIN INGREDIENT */
interface Sweet
{
   void mawastatus();
}
class Burfi  implements Sweet
{
   public void mawastatus()
   {
          System.out.println("
 Burfi   has mawa as" + "

                               one of its main ingredient");
   }
};
class Kajukatli implements Sweet
{
   public void mawastatus()
   {
          System.out.println("
 Kajukatli does not have
                mawa as " + "
 one of its main ingredient");
   }
};
class Jalebee implements Sweet
{
   public void mawastatus()
   {
          System.out.println("
 Jalebee does not have mawa
                as " + "
 one of its main ingredient ");
   }
};
class Rasgulla implements Sweet
{
   public void mawastatus()
   {
          System.out.println("
 Rasgulla does not have Mawa
                as" + "
 one of its main ingredient");
   }
}
class JPS8
{
   public static void main(String[] args)
   {
          Sweet ptr[] ={ new Burfi (), new Kajukatli(),
                       new Jalebee(), new Rasgulla() };
          for (int i = 0; i < 4; i++)
              ptr[i].mawastatus();
   }
}

OUTPUT:
Burfi   has mawa as
one of its main ingredient

Kajukatli does not have mawa as
one of its main ingredient

Jalebee does not have mawa as
one of its main ingredient

Rasgulla does not have mawa as
one of its main ingredient

Explanation: The interface Sweet declares one function mawastatus. Any class which inherits this class has to redefine this function and tell whether they contain mawa as one of its main ingredients. This interface Sweet is implemented, for example, by four different classes: Burfi, Kajukatli, Jalebee and Rusgulla. Each class does provide implementation of function mawastatus. In the main, an array of reference ptr of interface Sweet type is created . In the reference array ptr, the address of objects of four different classes are assigned.

Sweet ptr[] ={ new Burfi (), new Kajukatli(),
             new Jalebee(), new Rasgulla() };

In the for loop when mawastatus function is called using this reference array ptr, respective mawastatus functions of each class are called.

9.3.4 Extending Classes and Interfaces

When extending a class and an interface, the class must be extended first and then the keyword implements has to be used. This means that the keyword extends must come before the keyword implements. The general syntax is as follows:

class new_class extends old_class implements inter1, inter2,
 .....interN;
{
}

Use of class and inheritance together support the idea of multiple inheritances in Java. More than one interface can be implemented, but only one class can be extended. Diagrammatically, this can be shown as one, where a derived class has one base class and implements two interfaces.

images

An interface can extend another interface as shown in the following page.

interface inter1
{
    void fun1();
    void fun2();
}
interface inter2 extends inter1
{
    void fun3();
    void fun4();
    float limit = 23.99;
}

The interface inter2 inherits inter1. Any class which implements inter2 must provide implementation of all the four methods funx, where the value of x is from 1 to 4. The interface inter2 also defines one final static constant limit , which can be used in the implementing classes.

Interfaces can be used for declaring constants, i.e., an interface can be declared to work exactly like enum used in C/C++. For example:

interface days
{
   int SUN 1, MON = 2, TUE = 3, WED = 4, THU = 5, FRI = 6, SAT = 7;
}

Or

interface Months
{
   int JANUARY=1, FEBRUARY=2, MARCH=3, APRIAL=4,MAY=5,
          JUNE=6, JULY=7, AUGUST=8,SEPETEMBER=9,OCTOBER =10,
          NOVEMBER = 11, DECEMBER =12;
}

The constants can be used in Java programs by implementing the interface and using in the following way:

class demo implements days,months
{
   switch(x)
   {
          case MON:
                     .......    ;
                     break;
          case SUN:
                     .......    ;
          break;
          case TUE:
                     .......    ;
                     break;
          ................
   }
          if(month==JAN)
          ........
          else if(month == DEC)
          ........
}
/*PROG 9.5 EXTENDING CLASS, IMPLEMENTING INTERFACE */
interface i_demo
{
   void show();
}
class first
{
   void display()
   {
          System.out.println("
 Show of first");
   }
}
class second extends first implements i_demo
{
   public void show()
   {
          System.out.println("
 Show of second");
   }
}
class JPS9
{
   public static void main(String[] args)
   {
          second ref = new second();
          ref.show();
          ref.display();
   }
}
OUTPUT:
Show of second
Show of first

Explanation: In the program, the class second extends the class first and simultaneously implements interface i_demo. In the main, an object reference of the class second is created and the function show and display are called.

9.4 PONDERABLE POINTS

1.   A package is a collection of classes and interfaces.

2.   A package can be imported to an application using the import statement.

3.   Importing a package does not add to the size of the program.

4.   Importing a package explicitly means that all classes and interfaces are not imported rather the desired class/interface is imported by explicitly mentioning the name of class/interface.

5.   For creating a user-defined package package statement must be the first statement in the program file.

6.   Each import statement must be placed on a separate line.

7.   The CLASSPATH environment variable sets the path of classes used in the program.

8.   Before using a user-defined package CLASSPATH must have been set.

9.   An interface is a class where all the methods are declared but not defined and all fields are defined.

10. All the methods of an interface are by default abstract and the fields are static and final.

11. In order to make use of an interface, the keyword implements is used.

12. Interface allows simulating inheritance in Java.

13. While inheriting a class and interface to a class, the keyword extends must come first before the keyword implements.

14. A class can implement many interfaces but can extend only one class.

15. When implementing a method of an interface in a derived class, it must be preceded by the keyword public.

16. A reference of an interface can only call its methods and not the class in which it is implemented.

REVIEW QUESTIONS

1.   What is a package?

2.   What is the difference between implicit and explicit import statement? Which one takes less time for compilation? Justify.

3.   Write a code segment to use java.awt. Graphics

(a) Using import statement.

(b) Without using import statement.

4.   How is a package designed? Explain the procedure with the help of suitable example.

5.   What is the use of javac -d option?

6.   Write a package called Clear, it contains one public method clrscr() to clear the screen, import the package and use it in another programs. Add another public method starline(). It prints the line of 15 starts.

7.   What is the difference between public and default class.

8.   Discuss the various types of access protection in package, with example.

9.   Define interface. Give an example.

10. Compare and contrast the following:

(a) Interface and Class

(b) Interface and Abstract Class.

11. How to design and implement and interface?

12. How is one interface extended by the other?

13. Write a program in Java. A class Teacher contains two fields, Name and Qualification. Extend the class to Department, it contains Dept. No and Dept. Name. An interface named as College contains one field Name of the college. Using the above classes and Interface get the appropriate information and display it.

14. Justify the following statements: "import statement works much like the C/C++ #include statement".

15. Explain class path. What is the procedure to set user defined class path?

Multiple Choice Questions

1.   Which package provides classes necessary for the creation of applets and related operations?

(a) java.awt.event

(b) java.applet

(c) java.lang

(d) None of the above

2.   The dynamically changing part of program memory can be divided into

(a) stack memory area

(b) heap memory area

(c) both (a) and (b)

(d) none of the above

3.   A stack memory area is used to store the

(a) local variables declared in methods

(b) global variables

(c) static variable

(d) none of the above

4.   A heap memory area is used to store the

(a) local variables declared in methods

(b) global variables

(c) memory for objects

(d) none of the above

5.   An interface is a collection of

(a) constants

(b) variables

(c) classes

(d) constants and abstract methods

6.   A package is a collection of

(a) related classes

(b) related interfaces

(c) related classes and interfaces

(d) none of the above

7.   Java package is a grouping mechanism with the purpose of

(a) providing the library for Java program

(b) controlling the visibility of classes, interfaces and methods

(c) replacing header file used in C/C++

(d) none of the above

8.   The import statement given below:

1. import java.io.*;
2. import java.io. DataInput-
   Stream;

(a) 1- Explicit Import Statement, 2- Implicit Import Statement

(b) 1- Implicit Import Statement, 2- Explicit Import Statement

(c) 1-Implicit Impot Statement, 2- Implicit Import Statement

(d) 1-Explicit Import Statement, 2- Explicit Import Statement

9.   A class can implement many interfaces but can extend

(a) only one class

(b) two classes

(c) three classes

(d) no limit

10. Which of the following is used to make use of an interface?

(a) Import statement

(b) Extend

(c) Implements keyword

(d) None of the above

KEY FOR MULTIPLE CHOICE QUESTIONS

1.   b

2.   c

3.   a

4.   c

5.   d

6.   c

7.   b

8.   b

9.   a

10. c

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.35.194