Chapter 3: Interface and Package
Chapter 3: Interface and Package
CONTENTS
3.1 Interface
Define Interface
Implementing interface
Accessing interface Variables & methods
Extending interfaces
Interface references
Nested interfaces
3.2 Package
Define package
Type of package
Naming & creating packages
Import statement
Static import
Adding class & interfaces to a package.
Chapter 3: Interface and Package
3.1 Interface
QUESTIONS
o What is meant by an interface? State its need and write syntax and features of
an interface. Give one example.
o What is interface? How it is different from class? With suitable program
explain the use of interface.
Why do we use interface ?
It is used to achieve total abstraction.
Since java does not support multiple inheritance in case of class, but by using
interface it can achieve multiple inheritance .
Difference between class and interface
Basis for
Class Interface
Comparison
An interface can never be instantiated
A class is instantiated to create
Basic as the methods are unable to perform
objects.
any action on invoking.
Keyword class interface
The members of a class can be The members of an interface are
Access specifier
private, public or protected. always public.
The methods of a class are
The methods in an interface are purely
Methods defined to perform a specific
abstract.
action.
A class can implement any An interface can extend multiple
Implements/
number of interface and can interfaces but can not implement any
extends
extend only one class. interface.
An interface can never have a
A class can have constructors to
Constructor constructor as there is hardly any
initialize the variables.
variable to initialize.
Define Interface
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and multiple
inheritance in Java.
Writing an interface is similar to writing a class. But a class describes the attributes and
behaviors of an object. And an interface contains behaviors that a class implements.
An interface:
Chapter 3: Interface and Package
declares only method declarations and public constants.
cannot be instantiated.
can be implemented by a class.
cannot extend a class.
can extend several other interfaces.
Unless the class that implements the interface is abstract, all the methods of the interface need
to be defined in the class.
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 for implementation of these methods.
An interface is declared by using the interface keyword. It provides total abstraction; means
all the methods in an interface are declared with the empty body, and all the fields are public,
static and final by default. A class that implements an interface must implement all the
methods declared in the interface.
The general form of an interface definition is:
interface InterfaceName
{
Variables declaration;
Methods declaration;
}
Here, interface is the keyword and InterfaceName is any valid Java variables (just like class
names.)
Example:
interface Area
{
float pi = 3.14F;
float compute (float x, float y);
void show ();
}
In other words, Interface fields are public, static and final by default, and the methods are
public and abstract.
Chapter 3: Interface and Package
The relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends
another interface, but a class implements an interface.
Imp
lem
enti
ng
inte
rfac
e
Inte
rfac
es
are used as “super classes” whose properties are inherited by classes. It is therefore necessary
to create a class that inherits the given interface.
This is done as follows:
class classname implements InterfaceName
{
Body of classname
}
Example:
//Interface
interface Area //Interface Defined
{
float compute (float x, float y);
}
class Rectangle implements Area //Interface implemented
{
public float compute (float x, float y)
{
return x*y;
}
}
Accessing Interface variables and Methods
Interfaces 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
Chapter 3: Interface and Package
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 we can
use a final value.
Example:
interface A
{
int m = 10;
void show();
}
class B implements A
{
public void show()
{
System.out.println(“Value of m :: ” + m);
}
void method()
{
if(m>6)
show();
}
}
Extending Interfaces
Like classes interfaces can be extended. That is, an interface can be sub-interfaced from other
interfaces. The new sub-interface will inherit all the members of the super-interface in the
manner similar to subclasses.
This is achieved using the keyword extends as shown below:
interface name2 extends name1
{
Body of name2
}
Example:
interface ItemConstants
{
int code = 1001;
String name = “Fan”;
}
interface Item extends ItemConstants
{
void display();
}
[NOTE: An interface cannot extend classes.]
Chapter 3: Interface and Package
Interfaces References
We can declare variables as object references that use an interface rather than a class type.
Any instance of any class that implements the declared interface can be referred to by such a
variable.
When we call a method through one of these references, the correct version of the method
will be called based on the actual instance of the interface being referred to. This is one of the
key features of interfaces.
The method to be executed is looked up dynamically at run time, allows classes to be created
later than the code which calls methods on them. The “calling” code can dispatch through an
interface without having to know anything about the “callee”.
// accessing the class through interface reference
interface Mango
{
void display ();
}
class Summer implements Mango
{
public void display ()
{
System.out.println ("First Display method... ");
}
}
class Winter implements Mango
{
public void display ()
{
System.out.println ("Second Display method...");
}
}
class MyInterface
{
public static void main (String args[]) {
Summer s = new Summer ();
Winter n = new Winter ();
Mango m;
m = s; //assigning the reference
m.display ();
m = n; //assigning the reference
m.display ();
}
Chapter 3: Interface and Package
Nested Interfaces
An interface can be declared as the part of a class or another interface. Such interface is
called as nested interface or member interface. Unlike general interface, a nested interface
can be declared as public, private or protected. When a nested interface is used outside of its
enclosing scope, it must be qualified by the name of the class or interface of which it is
member. Thus, outside of the class or interface in which a nested interface is declared, its
name must be fully qualified.
// Nesting of the interfaces.
class CPU
{
public interface MicroProcessor
{
boolean isMultiCore(int core);
}
}
class Computer implements CPU, MicroProcessor
{
public boolean isMultiCore(int core)
{
if(core>1)
return true;
else
return false;
}
}
class NestInterface
{
public static void main(String args[])
{
CPU.MicroProcessor comp = new Computer();
int noOfCores = 4;
if (comp.isMultiCore(noOfCores))
System.out.println ("It is multi- core");
else
System.out.println ("It is single core");
}
}
Chapter 3: Interface and Package
Multiple inheritance
Multiple inheritances: It is a type of inheritance where a derived class may have more than
one parent class. It is not possible in case of java as you cannot have two classes at the parent
level Instead there can be one class and one interface at parent level to achieve multiple
interface.
Interface is similar to classes but can contain on final variables and abstract method.
Interfaces can be implemented to a derived class.
In order to understand the power of interfaces, let’s look at the practical example which
creates the multiple inheritance.
// implementing multiple inheritance
class Player
{
String name;
void getName(String n)
{
name = n;
}
void putName()
{
System.out.println("Name: "+name);
}
}
class Records extends Player
{
float avg, sRate;
void getData(float a, float s)
{
avg = a;
sRate = s;
}
void putData()
{
System.out.println("Records :- ");
System.out.println("Average: "+avg);
System.out.println("Strike rate: "+sRate);
}
}
interface IPL
{
void displayEarning();
Chapter 3: Interface and Package
}
interface Information
{
void getTeam(String t);
}
class Match extends Records implements IPL, Information
{
long earn;
Match(long e)
{
earn = e;
}
public void displayEarning()
{
System.out.print("His earning : "+earn);
System.out.println(" Rupees");
}
public void getTeam(String t)
{
System.out.println("Team: "+t);
}
}
class MultiInheritance
{
public static void main(String args[])
{
Match s = new Match(5600000);
s.getName("Shane Warne");
s.putName();
s.getTeam("Rajasthan Royals");
s.getData(30.52f, 123.45f);
s.putData();
s.displayEarning();
}
}
In program, it contains four classes and two interfaces. The hierarchy shown in figure below
has been created. The class ‘Match’ has been inherited from class ‘Records’ and implemented
from interfaces ‘IPL’ and ‘Information’. This creates a multiple inheritance. The interfaces
‘IPL’ and ‘Information’ can also be implemented in other classes such as ‘Player’ and
‘Records’. So after compiling the source file six different .class files will be created including
classes and interfaces.
Chapter 3: Interface and Package
Player
IPL Records Information
Match
Fig. multiple inheritance using interface
3.2 Package
QUESTIONS
o What is package? How to create package? Explain with suitable example
o What is package? State any four system packages along with their use? How
to add class to a user defined package?
Define package
Packages are Java’s way of grouping a variety of classes and/or interfaces together.
That is, a package is called as the collection of classes and interfaces.
It can be called as the container for classes that is used to keep the class name space
compartmentalized.
Packages are stored in a hierarchical manner and are explicitly imported into new
class definitions. By organizing the classes and interfaces into packages we can
achieve the following goals:
1. Classes contained in packages of other programs can be easily reused.
2. Two classes in two different packages can have same name but they should be
referred by their fully qualified name.
3. Packages provide a way of hiding classes. So we can prevent them from accessing
outside.
4. Packages provide a way of separating ‘design’ from ‘coding’. We can design
classes and decide their relationships and then we can implement the Java code
needed for the methods. It is also possible to change the implementation of any
method without affecting the rest of the design.
Type of package
Java packages are classified into two types:
1. Java API packages (System Packages)
2. User Defined Packages
Java API Packages
Chapter 3: Interface and Package
Java API (Application Program Interface) library provides a large number of classes grouped
into different packages according to functionality. Many times we use the packages available
with the Java API.
For example, while using the println( ) method we have to use the java.lang package which is
by default imported in a Java program.
Fig. below shows the fundamental packages that are frequently used in a Java program.
java
lang io util awt applet
Fig. Frequently used Java packages
The classes that are included in these packages are:
java.lang – Language support classes such as System, Thread, Exception etc.
java.util – Utility classes such as Vector, Arrays, LinkedList, Stack etc.
java.io – Input output support classes such as BufferedReader, InputStream
java.awt – Classes using GUI such as Window, Frame, Panel etc.
java.applet – Classes for creating and implementing applets.
Naming & creating packages
Naming conventions for packages
Package names can be given using standard Java naming conventions rules.
By this convention, the package name begins with lower case letter. This make easy to
distinguish between the class or interface and package name by looking at them. Because by
naming conventions, the first letter of a class name is always upper case letter.
For example look at the statement:
double x = java.lang.Math.sqrt(10);
This statement uses the fully qualified name of the class Math to use method sqrt ( ). Note
that the method name begins with a lower case letter.
Every package name must be unique to make the best use of packages. Duplicate names will
cause the run-time errors.
Since multiple users work on the Internet, duplicate package names are unavoidable. Java
developers have recognized this problem and thus suggested a package naming convention to
ensure its uniqueness.
Chapter 3: Interface and Package
For example:
soc.col.mypackage
Here ‘soc’ denotes society name and ‘col’ denotes the college name. We can create the
hierarchy of packages within packages by separating the levels by dot.
Creating the package
Creating a package is quite easy. We just have to include a package command as the first
statement in a Java source file.
Then any classes declared within that file will automatically belong to the specified package.
The package statement defines a name space in which classes are stored. If we omit the
package statement, the class names are put into the default package, which has no name.
(This is why we haven’t had to worry about packages before now.)
Most of the time, we will define a package for our 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;
public class MyClass
{
//body of the class
}
Here myPackage is the name of package. The class MyClass is now considered as the part of
this package. Java uses file system directories to store packages.
Steps to create packages:
1. Declare the package at the beginning of a file using the form:
package packagename;
2. Define the class that is to be put int the package and declare it public.
3. Create a subdirectory under the directory where the main source files are stored.
4. Store the listing as the classname.java file in the java subdirectory created.
5. Compile the file. This creates .class file in the subdirectory.
A java package file can have more than one class definitions. In such cases, only one of the
classes may be declared public and that class name with .java extension is the source file
name. When a source file with more than one class definition is compiled, Java creates
independent .class files for those classes.
Chapter 3: Interface and Package
Import statement
To access any package in any class, first we should import the package using Import
statement.
Syntax:
import packagename.classname;
or
import packagename.*;
It must appear at the top of the file, before any class declarations, import keyword is
used.
The first statement allows the specified class in the specified package to be imported.
For example,
import java.util. Scanner;
It imports the Scanner class and therefore the class name can now be directly used in
the program.
The second statement imports every class contained in the specified package.
For example,
import java.util.*;
Will bring all classes of java.util package.
Static import
Static import extend the capabilities of the import keyword. By following import keyword
with static, an import statement can be used to import static members of the class or interface.
By using static import, it is possible to refer static members of the class directly by their
names. They need not have to refer the class name with them. This simplifies the syntax
required to use the static member.
Let’s begin this concept with an example which uses three different static methods from
three different classes. The ‘Math’ class from lang package contains a static method called
‘sqrt( )’ which finds the square root of the number.
//Non static import method
class NonStaticImport
{ public static void main(String args[])
{
double x = Math.sqrt(52); //method1
System.out.print("Square root of 52: ");
System.out.println(x); //method2
char ch = 'D';
if (Character. isUpperCase(ch)) //method3
System.out.println(ch+" is uppercase");
Chapter 3: Interface and Package
}
}
Program uses three static methods that are sqrt ( ) of Math class, println ( ) of System
class and isUpperCase ( ) of Character class. All these are the part of java.lang package.
While using these methods in program we have to refer them by using the class name
along with them. We can eliminate this by importing these methods using static import as
shown in program below. This is modified version of program shown above.
//Static import
import static java.lang.Math.sqrt;
import static java.lang.Character.isUpperCase;
import static java.lang.System.out;
class StaticImport
{ public static void main(String args[])
{ double x = sqrt(52); //method1
out.print("Square root of 52: ");
out.println(x); //method2
char ch = 'D';
if(isUpperCase(ch)) //method3
out.println(ch+" is uppercase");
}
}
Here all three methods are brought into view by the static import statements:
import static java.lang.Math.sqrt;
import static java.lang.Character.isUpperCase;
import static java.lang.System.out;
After these statements, it is no longer necessary to qualify sqrt( ), println( ) and
isUpperCase( ) with their class name. Therefore the statements method1, method2 and
method3 are more simplified. It is considerably more readable.
There are two general form of the static import statement.
The first form which brings a particular method into view. Its general form is:
import static packagename.classname.methodname;
Second form of static import imports all static members of given class or interface into
view. Its general form is:
import static packagename.classname.*;
This will import all static members of particular classname from packagename into view
of the program.
For example:
Chapter 3: Interface and Package
import static java.lang.Math.*;
import static java.lang.Character.*;
By writing these statements in the program we can use pow ( ), log( ), sin( ) as well as
other static methods of Math class to refer directly by their names. The Character class
static methods such as isLowerCase( ), toUpperCase( ) can also be used referred directly.
Adding class & interfaces to a package.
It is simple to add a class & interface to an existing package. Consider the following package:
package p1;
interface A
{
Body of A
}
public class B
{
Body of B
}
The package p1 contains one public class by name B and interface by name A
Suppose we want to add another class C and interface D to this package. this can be done as
follows:
1. Define the class and interface and make it public.
2. Place the package statement : package p1;
before the class and interface definition as follows:
package p1;
interface D
{
…….
}
public class C
{
………
}
3. Store this as C.java file under the directory p1.
4. Compile C.java file. This will create B.class file and place it in the directory p1.
[NOTE: we can also add a non – public class to a package using the same
procedure.]
Remember that, since a Java source file can have only one class declared as public,
we cannot put two or more public classes together in a .java file. This is because of
the restrictions that the file name should be same as the name of the public class with
.java extension.
Access Protection
Chapter 3: Interface and Package
private default protected public private
protected
Same class Yes Yes Yes Yes Yes
Same package Yes
No Yes Yes Yes
subclass
Same package no No
No Yes Yes Yes
subclass
Different
package subclass No No Yes Yes Yes
Different
package no subclass No No No Yes No