Chapter 5 Interface
Chapter 5 Interface
BY
P RAT I M A S A R KA R
CSE TINT
Interface
Using the keyword interface, you can fully abstract a class’ interface from its implementation.
That is, using interface, you can specify what a class must do, but not how it does it.
Interfaces are syntactically similar to classes, but they lack instance variables, and their methods
are declared without any body.
In interface variables are final and static.
In interface methods are public and abstract.
Once it is defined, any number of classes can implement an interface. Also, one class can
implement any number of interfaces (multiple inheritance).
Interface
To implement an interface, a class must create the complete set of methods declared by the
interface.
However, each class is free to determine the details of its own implementation.
By providing the interface keyword, Java allows you to fully utilize the “one interface, multiple
methods” aspect of polymorphism.
Interfaces are designed to support dynamic method resolution at run time.
Why use Java interface?
here are mainly three reasons to use interface. They are given below.
It is used to achieve abstraction.
By interface, we can support the functionality of multiple inheritance.
It can be used to achieve runtime polymorphism.
How to declare an interface?
access interface name
{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
Internal addition by the
compiler
The relationship between classes
and interfaces
Example
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
class A implements S{ {
public void callme(){ S s1; //reference of interface S
S.o.pln (“inside A”); }} A a1=new A();
B b1=new B();
class B implements S{
public void callme() s1=a1;
{ s1.callme()// calls A’s version
S.o.pln (“inside B”); s1=b1;
}}
s1.callme() // calls B’s version
}}
Thank You