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;