10 Packages and Interfaces — Java Programming
10.1 Introduction
In this chapter, you will learn about how to define your own packages and a way of achieving multiple inheritance, which is done through interfaces. Thus, we consider the second form of reuse that is, reuse through polymorphism and learn how Java’s Interface mechanism supports this form of reuse. We will also compare interfaces and inheritance and inheritance.
10.2 Packages
Packages are containers for classes that are used to keep the class name space compartmentalized. Usually for all the Java programs we compile a .class file generated. Once a .class file is generated, we cannot have another .class file with same name. So, a programmer has to restrict himself while naming his classes. Here we use packages for flexibility. The package is both a naming and a visibility control mechanism. We can define classes inside a package that are not accessible by code outside that package. But the classes inside the package may have access.
Package definition
The general form of package is:
package pkgname;
We can have a hierarchy of packages..
The general form if a hierarchy of packages is
package pkg1[.pkg2[.pkg3]];
This is a multileveled package statement.
For example consider the package java.lang.ref
Package means java/lang/ref in the system. Hence according to the package definition, the directories should be created.
10.3 The CLASSPATH
CLASSPATH is an environment variable. All the programs we have executed so far have run well even though we have not used packages. This is because, CLASSPATH variable is set to the current working directory. And all the classes generated are in this directory. So, Java runtime considered this by default.
Creating a package and setting the CLASSPATH, is done like this. If your working directory is C:\jdk-16\bin then,
At c>type set as below
c>set
you will get all the variables and the values to which they are set. We need to set CLASSPATH and PATH. PATH is assigned a value currently. To that append string c:\jdk\bin. Then, set the CLASSPATH.
C> set CLASSPATH=.; c:\jdk\bin;c:\windows\java\classes
Now in, jdk\bin, create a directory mypkg. Now type and test the following programs.
Some standard packages are:
java.lang: The package for language. This is automatically imported in every class.
java.io: It contains all the classes that handle device independent i/o, files, and so on. This is automatically imported.
java.net: This contains classes that provide network functions, used for communication between computers.
java.util: This contains classes for system data, random number generation, data structure such as stacks and heaps.
Java.awt: This provides classes that create windows. And there are classes for windows, buttons, scroll bars etc.,
java.apple: Has classes related to applets.
Program 10.1 Write a program to demonstrate package
// mypkg/student.java put this file in mypkg folder //Click here for code package mypkg; public class student { int rollno; int marks; public student(int n,int m) { rollno=n; marks=m; } public void display() { System.out.println("rollno="+rollno+"marks="+marks); } } // C>mypkg>javac student.java. Now see that the class file is in mypkg folder
//studentClass.java import mypkg.student; public class studentClass { public static void main(String args[]) { student stud= new student(25,90); stud.display(); } }
/* C>javac studentClass.java C> java studentClass.java Output: rollno=25 marks=90 */
Anything declared public can be accessed from anywhere. Anything declared private in a class cannot be seen outside that class. When a member does not have an explicit access specification, it is visible to subclasses as well as to other classes in the same package. This is the default access. If you want to allow an element to be seen outside your current packages, but only to classes that subclass your class directly, then declare it as protected.
10.4 Class member access
The following table illustrates the access level.
|
|
Private |
No modifier |
Protected |
Public |
|
Same class |
Yes |
Yes |
Yes |
Yes |
|
Same package subclass |
No |
Yes |
Yes |
Yes |
|
Same package non subclass |
No |
Yes |
Yes |
Yes |
|
Different package subclass |
No |
No |
Yes |
Yes |
|
Different package non-subclass |
No |
No |
No |
Yes |
10.5 Importing packages
Once packages of classes are written, we can use a class or the package of classes in another program’s class.
The general form of using package is:
importpkg1[.pkg2].(classname or *);
Classname is optional.
For example
java.io.*; java.util.date;
Program 10.2 Write a program to demonstrate use of user created packages.
//student.java package mypkg; public class student{ int rollno; int marks; public student(int n, int m){ rolno=n; marks=m; } public void display(){ System.out.println(“rollno=”+rollno+”marks=”+marks); } } /* compile the above code as per the commands sjown below the source code and copy the .class file generated to ..\mypkg. */ //studClass.java //The following is the code studClass.java which is also in //c:\java\bin import mypkg.student; class studclass{ public static void main(String args[]){ student stud[]=new student[3]; stud[0]=new student(25,90); stud[1]=new student(26,93); stud[2]=new student(27,79); for(int i=0;i<3;i++) stud[i].display(); } } /* rollno=25marks=90 rollno=26marks=93 rollno=27marks=79 */
10.6 Interfaces
Interface is an important concept in Java through which multiple inheritance is achieved. With interface we can specify what a class must do, but not how it does it. Once defined, any number of classes can implement an interface. One class can implement any number of inheritances. This is one aspect of polymorphism. We think of an interface as a pure abstract class. It allows the creator to establish the form for a class: method names, arguments lists and returns types, but no method bodies. An interface can also contain data members of primitive types, but these are implicitly public, static and final. An interface provides only a form, but not implementation. Methods in interface are public and abstract.
To create an interface, use the inheritance key word instead of class keyword. Like a class, you can add the public keyword before the interface keyword(but only if that interface is defined in a file of same name) or leave it off to give ‘friendly’ status. The methods in the interface must be public. We must code every method in interface.
We can also extend an interface with inheritance.
interface p1{ — — } interface p2 extends p1{ — — }
//Program 10.3 Write a program to demonstrate the use of variables in interfaces.
//printGrade.java //click here for code import java.util.*; interface markgrade{ int distinction=0; int first=1; int second=2; int third=3; int fail=4; } class marks implements markgrade{ Random rand=new Random(); int findgrade(){ int mark=(int)(100*rand.nextDouble()); System.out.println("marks="+mark+" Result="); if(mark<40) return fail; else if(mark>=40 && mark <50) return third; else if(mark>=50 && mark <60) return third; else if(mark>60 && mark <70) return third; else return distinction; } } class printGrade implements markgrade{ static void answer(int result){ switch(result){ case distinction: System.out.println("Distinction"); break; case first: System.out.println("first"); break; case second: System.out.println("second"); break; case third: System.out.println("third"); break; case fail: System.out.println("fail"); break; } } public static void main(String args[]){ marks m= new marks(); answer(m.findgrade()); answer(m.findgrade()); answer(m.findgrade()); answer(m.findgrade()); } } /* Output: marks=33 Result= fail marks=36 Result= fail marks=51 Result= third marks=29 Result= fail */
10.7 Use of interfaces
1. An abstract can be defined and methods can be implemented later.
2. We can put restrictions on access of members thus producing security.
3. We can declare methods that can be implemented later.
4. We can inherit properties of several classes thus achieving multiple inheritance.
10.8 Summary
In this chapter, you have learned about packages, their definition, usage and different ways of implementing interfaces.