Java Interface

Aseen Saxena
2 min readApr 12, 2019

Java interfaces is a mechanism which allows a numbers of classes to share number of methods and constants. It also a good mechanism to use in polymorphism. In java interfaces method are declared as default abstract i.e. only method signature, body.

Some points when working with java interfaces:-

· Interface is the blue print of a class.

· Interface defines that what a class must do but do not define how it will do.

· Interfaces are used for full abstraction.

· We can use one or more interface in a class.

Syntax of java interface:

Interface<interface_name>

{

//declare methods that abstract

//declare constants fields

//by default

}

first we have to write “interface” keyword. Than all the methods in interface are declared with empty body and are public and all fields are public, static and final by default.

Advantages of using interfaces

· Interfaces can be used for total abstraction.

· Interfaces also help to achieve loose coupling.

· Interfaces can also support multiple inheritance.

Example of an interface in java

interface Test

{

public void m1();

public void m2();

}

class Test2 implements Test

{

public void m1()

{

System.out.println(“m1”);

}

public void m2()

{

System.out.println(“m2”);

}

public static void main(String arg[])

{

Test obj = new Test2();

obj.m1();

}

}

Output:- m1

New features added interfaces in JDK 8

· Before it is not possible for implementation of interfaces. We can now add default implementation for interface methods.

For example, if we need to add function which is already exist in interface. So the old code will not able to execute because classes have not implemented those new functions. Now in new version with the help of default implementation, we will give a default body for the newly added functions. So that old code can also run.

· And second we can now define static methods in interfaces which is also known as independently without an object.

· And in JDK 9 new features are added are static methods, private methods and private static method.

Interfaces and Inheritance in Java

A class can inherit another class and can implement one or more interface.

//Java program to implement a class can implement multiple interfaces

import java.io.*;

interface intI

{

void a1();

}

interface intF

{

void a2();

}

class test implement intF,intI

{

public void a1()

{

System.out.println(“Welcome to java”);

}

public void a2()

{

System.out.println(“This is aseen”);

}

}

class Aseen

{

public static void main(String args[])

{

test ob=new test();

ob.a1();

ov.a2();

}

}

Output:

--

--