top of page

Interface Changes in JAVA 8

Writer's picture: Dhruv PatelDhruv Patel

 

What is an interface in JAVA?

Interfaces are there to provide abstraction, providing only functionality to user and hiding complex implementations of the particular feature or function.

  • Prior to java 8, interface should have only abstract methods (methods without body)

  • Java 8 allows the interfaces to have default and static methods

What is the advantage of having Default & Static methods in java 8?

  • Default & Static methods provides backward compatibility.


For example, if classes such as Car , Truck and Bus implements an interface Vehicle then if we add a new method to the Vehicle, we have to change the code in all the classes (Car , Truck and Bus) that implements this interface.

It gives compile time error until cleanVehicle() method can not get override in all the classes.

In this example we have only three classes that implements the interface, but imagine if there are hundreds of classes implementing an interface it will become very difficult to change all the classes which are implementing that interface. This is why in java 8, we have a new concept “default methods”.


Default methods can be added to any existing interface and we do not need to implement these methods in the implementation classes (if required we can override them in implementation classes).


An interface only contains abstract methods. No method body only method declaration.

But, after JAVA 8 we can have default and static method in the interface which are concrete method. But why they are came up with this idea ? Let's understand....


Some key points about default methods are :

  • A default method must have a body.

  • The access modifier of default methods are implicitly public.

  • The class implementing such interface are not required to implement default methods. If needed, implementing class can override default methods

Static Methods In Java


The static methods in interfaces are similar to default methods but the only difference is that you can’t override them. Now, why do we need static methods in interfaces if we already have default methods?


Suppose you want to provide some implementation in your interface and you don’t want this implementation to be overridden in the implementing class, then you can declare the method as static.


Some key points about static methods are

  • A static method must have a body.

  • The access modifier of static methods is implicitly public.

  • This method must be called using interface name.

  • Since these methods are static, we cannot override them in implementing class.

27 views0 comments

Recent Posts

See All

Battle of the Backends: Java vs Node.js

Comparing Java and Node.js involves contrasting two distinct platforms commonly used in backend development. Here’s a breakdown of their...

Kommentare


bottom of page