Interface in Java

  • An interface is a template that contains constant and method declaration. The class that inherits from an interface must implement those methods.
  • An interface is declared using interface keyword followed by interface name.
  • In UML diagram, an interface is represented by a circle or a rectangle having the text <<interface>>.
  • You cannot apply protected or private access modifier to a top-level interface.
  • Variables declared in interfaces are public, final, and static by default.
  • Methods declared inside interfaces are implicitly public and abstract.
  • In other words, the interface only supports public access modifier to all of its members. In case you apply any other access modifier, it will give compile time error.

Syntax

access-modifier interface InterfaceName
{
	//constants and method declarations
}

Relationship Between Class and Interface

  • A class can extend another class using extends keyword.
  • A class can implement an interface using implements keyword.
  • An interface can extend another interface using extends keyword. It cannot extend a class.
Relationship Between Class and Interface

Example of interface

interface Father
{
	int f = 1;
	void printFather();
}
interface Child extends Father
{
	int c = 2;
	void printChild();
}
class GrandSon implements Child
{
	public void printFather()
	{
		System.out.println("f = "+f);
	}
	public void printChild()
	{
		System.out.println("c = "+c);
	}
	public static void main(String args[])
	{
		GrandSon g = new GrandSon();
		g.printFather();
		g.printChild();
	}
}

Output

f = 1
c = 2

Multiple Inheritance in Java

In Java, you can achieve multiple inheritance with the help of interface. A class can implement one or more interface and an interface can extend one or more interface.

Multiple Inheritance in Java

Example of Multiple Inheritance

interface Father
{
	int f = 1;
	void printFather();
}
interface Mother
{
	int m = 2;
	void printMother();
}
interface Child extends Father, Mother
{
	int c = 3;
	void printChild();	
}
class GrandSon implements Child
{
	public void printFather()
	{
		System.out.println("f = "+f);
	}
	public void printMother()
	{
		System.out.println("m = "+m);
	}
	public void printChild()
	{
		System.out.println("c = "+c);
	}
	public static void main(String args[])
	{
		GrandSon g = new GrandSon();
		g.printFather();
		g.printMother();
		g.printChild();
	}
}

Output

f = 1
m = 2
c = 3

Difference Between Abstract Class and Interface

abstract Class Interface
An abstract class may or may not have abstract method. All the methods inside an interface are by default abstract.
An abstract class can contain constructor. You cannot define constructor in an interface.
In an abstract class, the data variable may or may not be defined constant. An interface can only have constants.
It supports single level inheritance. It supports multiple inheritance.