Interface in Java
PRESENTED BY:
PRAJJAVAL RAO CHINTAL
What is an interface
An interface in java is a blueprint of a class. It has
static constants and abstract methods.
The interface in Java is a mechanism to achieve
abstraction.
It is used to achieve abstraction and multiple
inheritance in Java.
Why use Java interface?
It is used to achieve abstraction.
By interface, we can support the functionality of
multiple inheritance.
It can be used to achieve loose coupling.
Multiple inheritance is not supported
through class in java, but it is possible by
an interface, why?
multiple inheritance is not supported in the case of
class because of ambiguity.
However, it is supported in case of an interface
because there is no ambiguity. It is because its
implementation is provided by the implementation
class.
How to declare an interface?
An interface is declared by using the interface
keyword.
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.
Syntax:
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
Working of compiler
The Java compiler adds public and abstract
keywords before the interface method. Moreover, it
adds public, static and final keywords before data
members.
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.
Java Interface Example
//Interface declaration: by first user [Link]("drawing circle");
interface Drawable
{ }
void draw(); }
} //Using interface: by third user
//Implementation: by second user public class TestInterface1
class Rectangle implements Drawable {
{ public static void main(String args[])
public void draw() {
{ Drawable d=new Circle();//In real
[Link]("drawing scenario, object is provided by
rectangle"); method e.g. getDrawable()
Drawable r=new Rectangle();
} [Link]();
} [Link]();
class Circle implements Drawable }
{ }
public void draw()
{
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an
interface extends multiple interfaces, it is known as
multiple inheritance.
Multiple inheritance using interface
interface Printable }
{ public void show()
void print(); {
} [Link]("Welcome");
interface Showable
{ }
void show();
} public static void main(String
public class A7 implements args[])
Printable,Showable {
{ A7 obj = new A7();
public void print() [Link]();
{ [Link]();
[Link]("Hello"); }
}