Saturday, 28 October 2017

interface in Java

interface keyword

An interface is a keyword in java, it is used to declare interface in java. Like a class, interface can have methods and variables, but the methods declared in interface must be abstract. It is used to achieve abstraction and multiple inheritance in java. Methods in an interface are implicitly public.

Writing interface similar to writing a class. But class describes the attributes and behaviours of an object. And an interface contains behaviours that a class implements.  

Syntax to declare interface:

interface <interface-name>{

//abstract methods



interface Add{

public int add( );


How to implement interface

A class uses implement keyword to implement an interface. If class does not define all the methods of interface then the class must be declared as abstract.

Now we will explain how to implement an interface via this following example.



interface Add{

public int add( int a, int b);


class Complete implements Add{

public int add(int a, int b){

return a+b;



public class Sum{

public static void main(String [ ]q){

Complete obj=new Complete();

int c=obj.add(5,12);

System.out.println("Sum of  two numbers is "+c);




Sum of two numbers is 17

Code explanation:

In this program First we created one interface named as Add and then after we implement this interface by Complete class and this Complete class define the method that is declared inside interface. Now we create third class named as Sum and this class contains main method. Inside this main method we create object of Complete class and via this object we access the method and get the value of addition of two numbers. After getting the addition of two numbers we print that value using System.out.println( ).


Since java 8, interface can have default and static methods.

No comments:

Post a Comment