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.
public interface Fruits { default void nature(){ System.out.println("I am Sweet."); } }
The default methods are non-static and can be accessed from the Implementing class object as shown in the below example.
public class OrangeClass implements Fruits { public static void main(String[] args) { Fruits fruit = new OrangeClass(); fruit.nature(); } }
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.
Join CoinBase
! We'll both receive $10 in free Bitcoin when they buy or sell their first $100 on Coinbase! Available in India also.
Use the referral Join coinbase!
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.
Webull
! Receive free stock by signing up using the link: Webull signup.
More Related questions...