Interface in Java

Interface is a blue-print of a class which consists of abstract methods.

It is similar to class and it is one of the mechanism of data abstraction.

General Syntax

interface interface-name{

//fields or methods

}


To implement or use a interface in a class

class class_name implements interface_name{

//fields or methods declaration

}


Example

interface Vehicle{

void start();

void gearchange();

void stop();

}

class Bike implements Vehicle{

public void start(){

System.out.println("Bike is started");

}

public void gearchange(){

System.out.println("Gear is changed");

}

public void stop(){

System.out.println("Bike is stopped");

}

public static void main(String args[]){

Bike yamaha=new Bike();

yamaha.start();

yamaha.stop();

}

}

Try In Editor

Output

Bike is started

Vehicle is stopped

Methods inside the interface are abstract by default.


We cannot define the body or implementation of any method in a interface.

Example

interface Vehicle{

void start(){

System.out.println("Bike is started");

}

void gearchange();

void stop();

}

class Bike implements Vehicle{

public void gearchange(){

System.out.println("Gear is changed");

}

public void stop(){

System.out.println("Bike is stopped");

}

public static void main(String args[]){

Bike yamaha=new Bike();

yamaha.start();

yamaha.stop();

}

}

Try In Editor

Output

error: interface abstract methods cannot have body


We must implement the abstract methods of a interface compulsarily in its implemented classes, if methods are not implemented in subclass compiler throws a error.

Example

interface Vehicle{

void start();

void gearchange();

void stop();

}

class Bike implements Vehicle{

public static void main(String args[]){

Bike yamaha=new Bike();

}

}

Try In Editor

Output

error: Bike is not abstract and does not override abstract method stop() in Vehicle


We can extend an interface with another interface, this is known as inheritance of interface.

Example

interface Mammals{

void eat();

}

interface Human extends Mammals{

void talk();

}

class HumanMain implements Human{

public void eat(){

System.out.println("Can eat");

}

public void talk(){

System.out.println("Can talk");

}

public static void main(String args[]){

HumanMain hm=new HumanMain();

hm.eat();

hm.talk();

}

}

Try In Editor

Output

Can eat

Can talk