Interfaces

  • An interface is just like Java Class, but it only has static constants and abstract method.
  • Java uses Interface to implement multiple inheritance.
  • A Java class can implement multiple Java Interfaces.
  • All methods in an interface are implicitly public and abstract.

Syntax

 interface{
 //methods
 }

To use an interface in your class, append the keyword "implements" after your class name followed by the interface name.

 

Example for Implementing Interface

 class Dog implements pet

 

Example

 interface Pet{
 public void test();
 }
 class Dog implements Pet{
 public void test(){
 System.out.println("Interface Method Implemented");
 }
 public static void main(String args[]){
 Pet p=new Dog();
 p.test();
 }
 }

Output

Interface Method Implemented

Difference between Class and Interface

Class Interface
In class, you can instantiate variable and create an object. In an interface, you can't instantiate variable and create an object.
Class can contain concrete(with implementation) methods The interface cannot contain concrete(with implementation) methods
The access specifiers used with classes are private, protected and public.

In Interface only one specifier is used- Public

Difference between Abstract Class and Interface

Abstract Class Interface
Abstract keyword is used to create an abstract class and it can be used with methods. Interface keyword is used to create an interface but it cannot be used with methods.
A class can extend only one abstract class. A class can implement more than one interface.
An abstract class can have both abstract and non-abstract methods. An interface can have only abstract methods.
Variables are not final by default. It may contain non-final variables. Variables are not final by default. It may contain non-final variables.
An abstract class can provide the implementation of an interface. An interface cannot provide the implementation of an abstract class.