Objects, through the methods they expose, define their
interaction with the outside world. An interface is a collection of instance
variables and instance methods without having any body, i.e., the methods do
not have any definition. Once an interface is declared, any number of classes
can implement that method. In other words, the classes contain all the members
of the interface and they implement the definition of the method declared in
the interface. By implementing an interface, we can achieve multiple and
hierarchical inheritance as well as achieve dynamic (run time) polymorphism.
Declaring an Interface
The syntax for declaring an interface is:
Listing 8
Accessspecifier interface interfacename
{
specifier datatype variable = value;
…
…
specifier returntype methodname(parameter);
…
…
}
In the above example interface is a keyword.
Access specifiers – This must be public or it can be omitted
as well. If the access specified is omitted, then the classes of the same
package can only implement that interface in which the interface is present and
if the access specified is public then classes of any package can implement the
interface.
Implementing an Interface
The classes which implement an interface contain all the
members of the interface as well as some of its own member. The syntax of implementing
an interface is a shown below.
Listing 9
class classname implements interfacename
{
own members;
public void display()
{
……
……
……
}
}
Example of implementing Interface
The example below shows the implementation of an interface
D2 having a function area.
Listing 10
interface D2
{
public void area(int x,int y);
}
class triangle implements D2
{
int base;
int height;
public void area(int x,int y)
{
int a;
base = x;
height = y;
a = ½*base*height;
System.out.println(“Area is:”+a);
}
}
class rectangle implements D2
{
int length;
int breadth;
public void area(int x,int y)
{
int a;
length = x;
breadth = y;
a = length*breadth;
System.out.println(“Area is:”+a);
}
}
class result
{
public static void main(String a[ ])
{
D2 d;
triangle t = new triangle();
d = t;
d.area(10,5);
rectangle r = new rectangle();
d = r;
r,area(3,4);
}
}
Here the function area () of interface D2 is first
implemented by the class triangle to calculate the area of a triangle and then
it is implemented by another class named rectangle for calculating the area of
a rectangle.
Inheritance in Interface
Look at the code sample given below.
Listing 11
interface a
{
public void x();
public void y();
}
interface b extends a
{
public void z();
}
class c implements a
{
methods of a to be declared
}
class c implements b
{
methods of a and b are to be declared
}
An interface can be derived from another interface. The
syntax of inheriting an interface is the same as inheriting a class. When a
class implements an interface, which is again inherited form another interface,
in such cases the class must define all the methods of the base interface as
well as the derived interface.