Interface in Java

Posted in Java By Raj On December 6, 2017

 

What is an Interface?  Interface contains only definitions of methods and static final fields which helps you to get 100  percent abstraction but, in Java 8 the definition of Interface is changed you can have default and static methods and in Java 9 you can also have private methods

Advantages of Interface

  • Java does not support multiple inheritances using classes but, using Interface you can achieve multiple inheritances
  • You can hide the implementation details using Interface
  • Very useful when you are designing API’s

You cannot create an object for Interface but, you can create a reference object

If you see the below code, the interface contains only method definitions but if you want to have method body’s you must implement all method definitions in the class which implements your Interface

Interface: Example

In the below code, we did not mention any access specifiers by default all methods consider as public abstract methods and fields are static final fields, you do not need to mention any specifiers

If you see the below code the Scooter class overrides all the methods which are defined in the vehicle Interface, you must implement all methods otherwise you will get compile time error

You cannot create object for an Interface but, you can create a reference, if you try to create an object then you will get compile time error

Extends Interface

Like java inheritance, you can also extend interface from another interface but, you must implement all methods in the class

Output:

Multiple Inheritance

Java does not support multiple inheritances but, with the help of interfaces it supports multiple inheritance, if you are new to inheritance then I would recommend you to check my other article on Inheritance in Java

Here, the applyBrake method exists in both Interfaces, but, the actual implementation happened in the Scooter class so, you will not face any ambiguity issue

Output :