KEMBAR78
Chapter 3 Notes | PDF | Class (Computer Programming) | Inheritance (Object Oriented Programming)
0% found this document useful (0 votes)
20 views11 pages

Chapter 3 Notes

Chapter 3 discusses interfaces and packages in Java, explaining that interfaces allow for multiple inheritance by enabling classes to implement multiple interfaces without the complexities of traditional multiple inheritance. It details how to define and implement interfaces, including extending interfaces and accessing interface variables. Additionally, the chapter covers the concept of packages for organizing classes, defining package structures, and managing access control within Java applications.

Uploaded by

Prashant Bhamare
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views11 pages

Chapter 3 Notes

Chapter 3 discusses interfaces and packages in Java, explaining that interfaces allow for multiple inheritance by enabling classes to implement multiple interfaces without the complexities of traditional multiple inheritance. It details how to define and implement interfaces, including extending interfaces and accessing interface variables. Additionally, the chapter covers the concept of packages for organizing classes, defining package structures, and managing access control within Java applications.

Uploaded by

Prashant Bhamare
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Chapter-3 INTERFACES AND PACKAGES

INTERFACE

Java does not support multiple inheritance. That is, classes in Java cannot have more
than one superclass. For instance, a definition like
class A extends B extends C

is not permitted in Java. However, the designers of Java could not overlook the
importance of multiple inheritance. A large number of real-life applications require the
use of multiple inheritance whereby we inheritance methods and properties from several,
distinct classes. Since C++ like implementation of rnultiple inheritance proves difficult
and adds complexity to the language, Java provides an alternate approach known as
interfaces to support the concept of multiple inheritance. Although a Java class cannot be
a subclass of more than one superclass, it can implement more than one interface,
thereby enabling us to create classes that build upon other classes without the problems
created by multiple inheritance.
DEFINING INTERFACES
An interface is basically a kind of class. Like classes, interfaces contain methods and variables
but with a major difference. The difference is that interfaces define only abstract methods and
final fields. This means that interfaces do not specify any code to implement these methods and
data fields contain only constants. Therefore, it is the responsibility of the class that implements an
interface to define the code implementation of these methods.
The syntax for defining an interface is very similar to that for defining a class. The general form
of an interface definition is:
interface InterfaceName
{
var iables declarat ion;
methods declaration;
}

Here, interface is the key word and InterfaceName is any valid Java variable (just like
class names). Variables are declared as follows:

static final type VariableName = Value;

Note that all variables are declared as constants. Methods declaration will contain only a list of
methods without anybody statements. Example:
return-type methodName1
(parameter_list);

Here is an example of an interface definition that contains two variables and one method:
interface Item
{
static final int code=1001;
static final String name =" Fan" ;
void display ( );
}
Note that the code for the method is not included in the interface and the method declaration
simply ends with a semicolon. The class that implements this interface must define the code for
the method. Another example of an interface is:
interface Area
{
f in al s ta ti c f lo at p i = 3. 14 2F ;
float compute (float x, float y);
void show ( );
}

E XT E ND IN G I NT E R FA CE S

Like classes, interfaces can also be extended. That is, an interface can be
subinterfaced from interfaces. The new subinterface will inherit all the members of the
superinterface in the manner similar to subclasses. This is achieved using the keyword
extends as shown below:
interface name2 extends name1
{
body of name2
}

For example, we can put all the constants in one interface and the methods in the other.
This will enable us to use the constants in classes where the methods are not required.
Example:
interface ItemConstants
{
int code = 1001;
string name = "Fan";
}
interface Item extends ItemConstants
{
void display ( );
}

The interface Item would inherit both the constants code and name into it. Note that
the variables name and code are declared like simple variables. It is allowed because all
the variables in an interface are treated as constants although the keywords final and
static are not present.
We can also combine several interfaces together into a single interface. Following
declarations are)
interface ItemConstants
{
int code = 1001; String
name - "Fan";
}
interface ItemMethods
{
void display( );
}
interface Item extends ItemConstants, ItemMethods
{
………………………………………….
………………………………………….
}

While interfaces are allowed to extend to other interfaces, subinterfaces cannot define
the methods declared in the superinterfaces. After all, subinterfaces are still interfaces,
not classes. Instead, it is the responsibility of any class that implements the derived
interface to define all the methods. Note that when an interface extends two or more
interfaces, they are separated by commas.
It is important two remember that an interface cannot extend classes. This would
violate the rule interface can have only abstract methods and constants.

IMPLEMENTING INTERFACES
Iterfaces are used as "superclasses" whose properties are inherited by classes. It is
therefore necessary to state a class that inherits the given interface. This is done as
follows:
class classname implements interfacename
{
body of classname
}

Here the class classname "implements" the interface interfacename. A more


general form of implementation may look like this:
class classname extends superclass
implements interfacel, interface2, .....
{
body of classname
}

This shows that a class can extend another class while implementing interfaces.
When a class implements more than one interface, they are separated by a comma. The
implementation of interfaces can take various forms as illustrated in Fig
Various forms of interface implementation

Implementation of interfaces as class types is illustrated by Program. In this program, first we


create an interface Area and implement the same in two different classes, Rectangle and
Circle. We create an instance of each class using the new operator. Then we declare an object
of type Area, the interface class. Now, we assign the reference to the Rectangle object rect
to area. When we call the compute method of area, the compute method of Rectangle class
is invoked. We repeat the same thing with the Circle object.

/ / InterfaceTest java
interface Area / / Interface defined
{
final static float pi = 3.14F;
float compute (float x, float y);

}
class Rectangle implements Area // Interface implemented

{
public float compute (float x, float y)
{
return (x*y);
}

}
class Circle implements Area / / Another implementation
{
public float compute (float x, float y)
{
return (pi*x*x);
}
}
class InterfaceTest
{
public static void main(String args[ ])
{

R e ct an gl e re ct = n ew Re ct an gl e( ) ;
Circle cir = new Circle( );
Area area; // Interface object
area = rect; / / area refers to rect object
System.out.println("Area of Rectangle = ” + area.compute(10, 21));
// area refers to cir object
area = cir;
S y s t e m . o u t . p r i n t l n (" A r e a o f C i r c l e = ” + area.compute(10, 0));
}
}

The Output is as follows:


Area of Rectangle = 200
Area of Circle = 314

Any number of dissimilar classes can implement an interface. However, to implement the
methods, we need to refer to the class objects as types of the interface rather than types of their
respective classes. Note that if a class that implements an interface does not implement all the
methods of the interface, then class becomes an abstract class and cannot be instantiated.

ACCE S S ING INT E RFACE VARIAB L E S

Interlaces can be used to declare a set of constants that can be used in different classes. This is
similar to creating header files in C++ to contain a large number of constants. Since such
interfaces do not contain methods, there is no need to worry about implementing any methods.
The constant values will be available to any class that implements the interface. The values can
be used in any method, as part of any variable declaration, or anywhere where we can use a final
value. Example:

interface A
{
int m - 10;
int n = 50;
}

class B implements A
{
int x = m
void methodB(int size)
{

if (size < n)
}
}
Program illustrates the implementation of the concept of multiple inheritance using interfaces.
class Student
{
int rollNumber;
void getNumber(int n)
{
rollNumber = n;
}
void putNumber( )
{
System.out.println (" Roll No : " + rollNumber);
}
}
Class Test extends Student
{
float partl, part2;
void getMarks(float ml, float m2)
{
partl = ml;
part2 = m2;
}
void putMarks( )
{
System.out.println("Marks obtained ");
System.out.println("Part 1 = " + part 1);
System.out.println("Part 2 = " + part 2);
}
}

interface Sports
{
float sportWt = 6.0F;
void putwt( );
}
class Results extends Test implements Sports
{
float total;
public void putWt( )
{
System.out.println(“Sports Wt = “+ sportWt);
}
void display( )
{
total = partl + part2 + sportWt; putNumber( );
putMarks( );
putWt( );
System.out.println(“Total score = “+
total);
}
}

class Hybrid
{
public static void main (String args( ])
{
Results studentl = new Results( );
studentl.getNumber(1234);
studentl.getMarks(27.5F, 33.0F);
studentl.display( );
}
}
PACKAGES
Packages are containers for classes that are used to keep the class name space
compartmentalized. For example, a package allows you to create a class named List,
which you can store in your own package without concern that it will collide with some
other class named List stored elsewhere. Packages are stored in a hierarchical manner
and are explicitly imported into new class definitions. The name of each example class
was taken from the same name space. This means that a unique name had to be used for
each class to avoid name collisions. After a while, without some way to manage the name
space, you could run out of convenient, descriptive names for individual classes. You
also need some way to be assured that the name you choose for a class will be reasonably
unique and not collide with class names chosen by other programmers. The package is
both a naming and a visibility control mechanism. You can define classes inside a
package that are not accessible by code outside that package. You can also define class
members that are only exposed to other members of the same package. This allows your
classes to have intimate knowledge of each other, but not expose that knowledge to the
rest of the world.

Defining a Package
To create a package is quite easy: simply include a package command as the first
statement in a Java source file. Any classes declared within that file will belong to the
specified package. The package statement defines a name space in which classes are
stored. If you omit the package statement, the class names are put into the default
package, which has no name. (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 a package for your
code.
This is the general form of the package statement:
package pkg;

Here, pkg is the name of the package. For example, the following statement creates a
package called MyPackage.
package MyPackage;

Java uses file system directories to store packages. For example, the .class files for any
classes you declare to be part of MyPackage must be stored in a directory called
MyPackage. Remember that case is significant, and the directory name must match the
package name exactly. 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 pkg1[.pkg2[.pkg3]];
A package hierarchy must be reflected in the file system of your Java development
system. For example, a package declared as
package java.awt.image;

needs to be stored in java/awt/image, java\awt\image, or java:awt:image on your


UNIX, Windows, or Macintosh file system, respectively. Be sure to choose your package
names carefully. You cannot rename a package without renaming the directory in which
the classes are stored.

Finding Packages and CLASSPATH


By default, the Java run-time system uses the current working directory as its starting
point. Thus, if your package is in the current directory, or a subdirectory of the current
directory, it will be found. Second, you can specify a directory path or paths by setting
the CLASSPATH environmental variable.

For example, consider the following package specification.


package MyPack;

In order for a program to find MyPack, one of two things must be true. Either the
program is executed from a directory immediately above MyPack, or CLASSPATH
must be set to include the path to MyPack. The first alternative is the easiest (and doesn’t
require a change to CLASSPATH), but the second alternative lets your program find
MyPack no matter what directory the program is in. Ultimately, the choice is yours.
The easiest way to try the examples shown in this book is to simply create the package
directories below your current development directory, put the .class files into the
appropriate directories and then execute the programs from the development directory.
This is the approach assumed by the examples.

A Short Package Example


Keeping the preceding discussion in mind, you can try this simple package:
// A simple package
package MyPack;
class Balance {
String name;
double bal;
Balance(String n, double b) {
name = n;
bal = b;
}
void show() {
if(bal<0)
System.out.print("--> ");E JAVA LANGUAGE
System.out.println(name + ": $" + bal);
}
}
class AccountBalance {
public static void main(String args[]) {
Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for(int i=0; i<3; i++) current[i].show();
}
}
Call this file AccountBalance.java, and put it in a directory called MyPack. Next,
compile the file. Make sure that the resulting .class file is also in the MyPack directory.
Then try executing the AccountBalance class, using the following command line:
java MyPack.AccountBalance

Remember, you will need to be in the directory above MyPack when you execute this
command, or to have your CLASSPATH environmental variable set appropriately. As
explained, AccountBalance is now part of the package MyPack. This means that it
cannot be executed by itself. That is, you cannot use this command line:
java AccountBalance
AccountBalance must be qualified with its package name.

Access Protection
Packages add another dimension to access control. As you will see, Java provides many
levels of protection to allow fine-grained control over the visibility of variables and
methods within classes, subclasses, and packages. Classes and packages are both means
of encapsulating and containing the name space and scope of variables and methods.
Packages act as containers for classes and other subordinate packages. Classes act as
containers for data and code. The class is Java’s smallest unit of abstraction. Because of
the interplay between classes and packages, Java addresses four categories of visibility
for class members:
■ Subclasses in the same package
■ Non-subclasses in the same package
■ Subclasses in different packages
■ Classes that are neither in the same package nor subclasses
The three access specifiers, private, public, and protected, provide a variety of ways to
produce the many levels of access required by these categories. Table 9-1 sums up the
interactions. While Java’s access control mechanism may seem complicated, we can
simplify it as follows. Anything declared public can be accessed from anywhere.
Anything declared private cannot be seen outside of its 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 package, but only to classes that subclass your class directly,
then declare that element protected.
Table 9-1 applies only to members of classes. A class has only two possible access levels:
default and public. When a class is declared as public, it is accessible by any other code.
If a class has default access, then it can only be accessed by other code within its same
package.
Importing Packages
Java includes the import statement to bring certain classes, or entire packages, into
visibility. Once imported, a class can be referred to directly, using only its name. The
import statement is a convenience to the programmer and is not technically needed to
write a complete Java program. If you are going to refer to a few dozen classes in your
application, however, the import statement will save a lot of typing.
In a Java source file, import statements occur immediately following the package
statement (if it exists) and before any class definitions. This is the general form of the
import statement:
import pkg1[.pkg2].(classname|*);
THE JAVA LANGUAGE
Here, pkg1 is the name of a top-level package, and pkg2 is the name of a subordinate
package inside the outer package separated by a dot (.). There is no practical limit on the
depth of a package hierarchy, except that imposed by the file system. Finally, you specify
either an explicit classname or a star (*), which indicates that the Java compiler should
import the entire package. This code fragment shows both forms in use:

import java.util.Date;
import java.io.*;

All of the standard Java classes included with Java are stored in a package called java.
The basic language functions are stored in a package inside of the java package called
java.lang. Normally, you have to import every package or class that you want to use, but
since Java is useless without much of the functionality in java.lang, it is implicitly
imported by the compiler for all programs. This is equivalent to the following line being
at the top of all of your programs:
import java.lang.*;

If a class with the same name exists in two different packages that you import using the
star form, the compiler will remain silent, unless you try to use one of the classes. In that
case, you will get a compile-time error and have to explicitly name the class specifying
its package. Any place you use a class name, you can use its fully qualified name, which
includes its full package hierarchy. For example, this fragment uses an import statement:

import java.util.*;
class MyDate extends Date {
}
The same example without the import statement looks like this:
class MyDate extends java.util.Date {
}

As shown in Table 9-1, when a package is imported, only those items within the package
declared as public will be available to non-subclasses in the importing code. For
example, if you want the Balance class of the package MyPack shown earlier to be
available as a stand-alone class for general use outside of MyPack, then you will need to
declare it as public and put it into its own file, as shown here:
package MyPack;
/* Now, the Balance class, its constructor, and its
show() method are public. This means that they can
be used by non-subclass code outside their package.
*/
public class Balance {
String name;
double bal;
public Balance(String n, double b) {
name = n;
bal = b;
}
public void show() {
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}

As you can see, the Balance class is now public. Also, its constructor and its show( )
method are public, too. This means that they can be accessed by any type of code outside
the MyPack package. For example, here TestBalance imports MyPack and is then able
to make use of the Balance class:
import MyPack.*;
class TestBalance {
public static void main(String args[]) {
/* Because Balance is public, you may use Balance
class and call its constructor. */
Balance test = new Balance("J. J. Jaspers", 99.88);
test.show(); // you may also call show()
}
}

As an experiment, remove the public specifier from the Balance class and then try
compiling TestBalance. As explained, errors will result.

You might also like