Let’s learn interface in java.
Interface in java
Interface is collection of methods of abstract type (having only method declaration). Interface specify what class must do, not how to.
A class which implements interface should define each and every method in the class. Interface is used to implement multiple inheritance in java (represent IS-A relationship).
Syntax
interface InterfaceName { fields // by default interface fields are public static final methods // by default interface methods are abstract, public }
To implement interface ‘implements’ keyword is used. In the below example interface Vehicle has abstract method accelerate() and we can see implementation of accelerate() method in class BMW.
Interface example
interface Vehicle { public void accelerate(); } class BMW implements Vehicle { public void accelerate() { System.out.println("BMW accelerating..."); } public static void main(String[] args) { BMW obj = new BMW(); obj.accelerate(); } }
Output:
BMW accelerating…
In the above example we have declared interface Vehicle and we can see the implementation in the class BMW.
Relationship between a class and an interface is a class implements an interface, an interface extends interface and a class extends another class.
NOTE:
Why interface in java is used
- Used to achieve loose coupling.
- Used to achieve total abstraction.
- Used to achieve multiple inheritance.
Java 8 interface have static and default methods. An interface can have method body in java8. For example.
interface Car { void accelerate(); // we need to make it default method default void show() { System.out.println("in default method"); } } class Audi implements Car { public void accelerate() { System.out.println("accelerating audi"); } } public class Java8InterfaceExample { public static void main(String[] args) { Car obj = new Audi(); obj.accelerate(); obj.show(); } }
Output:
accelerating audi
in default method
Now let’s see an example on java8 static method in interface.
interface Shapes { void draw(); static int square(int s) { return s * s; } } class Square implements Shapes { public void draw() { System.out.println("draw square"); } } public class Java8StaticMethodExample { public static void main(String[] args) { Shapes obj = new Square(); obj.draw(); System.out.println(Shapes.square(7)); } }
Output:
draw square
49
Summary
- Interface methods do not have body.
- Interface methods are by default public and abstract.
- We cannot create object of an interface.
- Interfaces can only be implemented by class. This class must override all its methods.
- Attributes of an interface are by default public, static and final.
- An interface cannot have constructor.
- A class can implement more than one interface.
Also read – ArrayList in java