Interface in Java

In Java, interface is used to achieve abstraction in java. It is a blueprint of class. An interface is not a class, but it does help create classes. An interface is fully abstract; it has no fields, only method definitions. A class can implement an interface, and unless the class is abstract, it is forced to provide concrete implementations for them. Each method declared inside an interface is implicitly public and abstract, because methods need to be abstract to force implementing classes to provide implementations and are public, so classes have access to do so.

The only methods with concrete bodies in an interface are static methods and starting with Java 8, default methods. The interfaces cannot be instantiated, they do not have constructors.

Interfaces that declare no method definitions are called marker interfaces and have the purpose to mark classes for specific purposes. The most renowned Java marker interface is java.io.Serializable, which marks objects that can be serialized (their state can be saved to a binary file).

An interface can be declared in its own file as a top-level component, or nested inside another component. There are two types of interfaces: normal interfaces and annotations.

The difference between abstract classes and interfaces, and when one or the other should be used, becomes relevant in the context of inheritance. Java supports only single inheritance. This means a class can only have one superclass.

Advantages of Interface
  • Interface support multiple inheritance.
  • Interface help to achieve abstraction.
  • Interface help to achieve loose coupling.
Syntax
		interface interface_name {  
		// declare fields
		// abstract/private/default methods
		}
Example of Interface
		interface Animal {
		  public void animalSound(); // interface method (does not have a body)
		  public void sleep(); // interface method (does not have a body)
		}

		class Dog implements Animal {
		  public void animalSound() {
		    System.out.println("The Dog is: Barking");
		  }
		  public void sleep() {
		    System.out.println("zzzz");
		  }
		}


		class Main {
		  public static void main(String[] args) {
		    Dog myDog = new Dog();
		    myDog.animalSound();
		    myDog.sleep();
		  }
		}
Output

The Dog is: Barking

Zzzz

Multiple Interfaces
		interface Dog {
		  public void dogSound(); // interface method
		}

		interface Cat {
		  public void catSound(); // interface method
		}

		// DemoClass "implements" Dog and Cat
		class DemoClass implements Dog, Cat {
		  public void dogSound() {
		    System.out.println("Dog Bark");
		  }
		  public void catSound() {
		    System.out.println("Cat Meww");
		  }
		}

		class Main {
		  public static void main(String[] args) {
		    DemoClass myObj = new DemoClass();
		    myObj.dogSound();
		    myObj.catSound();
		  }
		}
Output

Dog Bark

Cat Meww

Copyright 1999- Ducat Creative, All rights reserved.