Java / Methods
Explain the Default method for interfaces in Java 8.
In Java 8, a new feature "default method implementation for interfaces" is introduced that facilitates backward compatibility for the old interfaces to leverage the lambda expression capability of Java 8 and also existing libraries implementing these interfaces need not have to provide its implementation for the new functionality/method added to the interface.
For example, java.util.List or Collection interface does not have forEach method declaration. Thus, calling such methods will break the collection framework implementations. Java 8 introduces default method so that List/Collection interface can have a default implementation of forEach method, and the class implementing these interfaces need not have to implement the same.
Thus default methods enable you to add new functionality to the interfaces of your libraries and ensure backward compatibility with the codes written using the older versions of those interfaces without having to implement the new functionality.
For creating a default method in Java interface, we need to use default keyword with the method signature.
The default methods are non-static and can be accessed from the Implementing class object as shown in the below example.
Java interface default methods are also known as Defender Methods or Virtual extension methods.
A default method cannot override a method from java.lang.Object class as interfaces does not extend Object.
Compilation error occurs when a class tries to implement two or more interfaces having a default method with the same signature.
Other than multiple inheritance, there is no significant difference between an abstract class and an interface in Java 8 by the addition of default method feature.
Dogecoin! Earn free bitcoins up to $250 now by signing up.
Earn bitcoins upto $250 (free), invest in other Cryptocurrencies when you signup with blockfi. Use the referral link: Signup now and earn!
Using BlockFi, don't just buy crypto - start earning on it. Open an interest account with up to 8.6% APY, trade currencies, or borrow money without selling your assets.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
More Related questions...