INTERFACES
● 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.
● There can be only abstract methods in Java interface not
method body.
● It is used to achieve abstraction and multiple inheritance in
Java.
WHY USE JAVA INTERFACE?
There are mainly 3 reasons to 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 loose coupling.
HOW TO DECLARE AN INTERFACE?
● 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 and interface Must implement all
the methods declared in the interface.
SYNTAX:
interface <interface_name>{
// declare constant field
// declare methods that abstract
// by default.
}
Example:
interface Animal {
void eat();
void sleep();
}
In this example, the Animal interface declares two method signatures: eat() and sleep().
Any class implementing the Animal interface must provide concrete implementations
for these methods.
EXTENDING INTERFACE IN JAVA
● In java, an interface can extend another interface.
● When an interface wants to extend another interface, it uses
the keyword extends.
● An interface cannot extend multiple interfaces.
● An interface can implement neither an interface nor a class.
● The class that implements child interface needs toprovide
code for all the methods defined in both child and parent
interfaces.
JAVA INTERFACE EXAMPLE
In this example, the Printable interface has only one method, and its implementation is provided in the A6 class.
File Name: InterfaceExample.java
interface printable{
void print(); }
class InterfaceExample implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
InterfaceExample obj = new InterfaceExample();
obj.print();
}}
OUTPUT: Hello
MULTIPLE INHERITANCE IN JAVA BY INTERFACE
If a class implements multiple interfaces, or an interface extends multiple
interfaces, it is known as multiple inheritance.