Interface In Java

Java Interface is very similar to a class which only accepts public or default access specifier. A Java interface is also very similar to abstract class because both of them supports the concept of abstraction and both cannot be instantiated.

Example of abstract class:

abstract class Test {
abstract void show();
Test(){
	System.out.println("Default constructor"); //constructor creation possible in abstract class
}
public static void main(String[] args) {
	System.out.println("In Main");
	Test obj; //reference creation possible.
	obj=new Test(); // ERROR, instantiation not possible.
}
	}

Abstraction in Java is divided into 3 level:-

  1. 100% abstraction or complete abstraction.
  2. 0-100% abstraction or partially abstract.
  3. 0% abstraction or completely concrete.

 

  • Class in Java supports 0% abstraction which means it cannot contain any abstract method.
  • Abstract class supports 0-100% abstraction which means it may contain abstract or concrete method.
  • Interface supports the concept of 100% abstraction that means an interface will never contain any concrete method.

Difference Between Abstract Class and Interface

java interface

Example of Interface:

interface Test {
int x=100;
public static final int y=10;
void show();
public abstract void display();
Test (){
	// ERROR, Interface cannot have constructor
}
}

The default nature of a class is always complete class i.e. 0% abstraction. Complete class always supports 2 rules:

  • It should not contain any abstract method.
  • The class should override (redesign) all the abstract method present in the super abstract class or super interface.

Level of Abstraction - An Example



interface Test {
//100% abstraction
	int x=100;
	void show();
	public abstract void display();
}
abstract class A implements Test{
// 0-100% abstraction
	A(){
		System.out.println("Default constructor of A");
	}
	public void display(){
		System.out.println("Display method in A");
	}
}
public class Demo extends A  {
// 0% abstraction
	Demo(){
		System.out.println("In default constructor of Demo");
	}
	public void show() {
		System.out.println("Implementing show method in Demo");
		
	}
	public static void main(String[] args) {
		Demo obj= new Demo();
		obj.show();
		obj.display();
		System.out.println(obj.x);
		
	}	
}
//OUTPUT

/*Default constructor of A
In default constructor of Demo
Implementing show method in Demo
Display method in A
100*/

Points to note from the above program:

  1. When we call the child constructor, parent class constructor is first searched and then the child.
  2. Extends keyword is used when a class inherits another class or abstract class.
  3. Implements keyword is used when a class inherits an Interface.