Interfaces

Posted on

 Using the keyword “interface” you can fully abstract a class interface from its implementation. i.e., using an interface you can specify what a class “must do but not how it dose it”.

         Interfaces are designed to support dynamic method resolution at runtime. Normally in order for a method to be called from one class to another, both the classes need to be present at compile time. So, that the Java compiler can check the method signatures are compatible. Inevitably in a system like this functionality gets pushed up higher and higher in the class hierarchy so that mechanisms will be available to more and more sub-class. Interfaces are designed to avoid this problem. They disconnect the definaction of a method from the inheritance hierarchy.

         In the practice we can define interfaces, which don’t make assumptions about they, are implemented. Once it is defined any no. of classes can implement an interface. Also one can implement any no. of interfaces.

         Java allows you to fully utilize the “one interface multiple method, the aspect of polymorphism”.

         Interfaces are similar to class except that it defines only methods without any body. An interface can be created in the following format.

interface interface_name
{
return_type method1([arguments]);
return_type method2([arguments]);
ЕЕ...........................................
}

         Once an interface has been defined a class can use the methods available in the interface in the following format.

class class_name implements interface_name
{
ЕЕЕ............
body of the class
ЕЕЕ...........
}

     An interface provides us a partial substitute for “multiple inheritance” in Java.

import java.lang.*;
interface MyStack
{
void Push(int x);
void Pop();
void Display();
}
class Stack implements MyStack
{
private int stck[];
private int tos;
Stack(int size)
{
stck=new int[size];
tos=-1;
}
public void Push(int x)
{
if (tos==stck.length-1)
{
System.out.println("Stack overflow ...");
return;
}
stck[++tos]=x;
}
public void Pop()
{
if (tos==-1)
{
System.out.println("Stack underflow ...");
return;
}
tos--;
}
public void Display()
{
System.out.println("Elements of the stack");
for(int i=tos;i>=0;i--)
System.out.println(stck[i]);
}
}
class App60
{
public static void main(String yck[])
{
Stack S=new Stack(3);
S.Push(10);
S.Push(20);
S.Push(30);
S.Display();
S.Push(40);
S.Pop();
S.Display();
}
}


output:

\>javac App60.java
\>java App60
Elements of the stack
30
20
10
Stack overflow ...
Elements of the stack
20
10

Leave a Reply

Your email address will not be published. Required fields are marked *