Advertisement

Explain default methods in interface in java8 with example?

Explain default methods in interface in java8 with example? Traditionally, a Java interface groups related methods together into a contract. Any class that
implements an interface must provide an implementation for each method defined by the

interface or inherit the implementation from a superclass. But this causes a problem when

library designers need to update an interface to add a new method.


Existing concrete classes (which may not be under their control) need to be modified to reflect the new interface
contract. This is particularly problematic because the Java 8 API introduces many new methods
on existing interfaces.


For Example Java collections library has been designed many years ago, and there is a
problem,if the Collection interface gets new methods, such as forEach, then
every program that defines its own class implementing Collection will break until
it, too, implements that method. That is simply unacceptable in Java.

Default methods are added to Java 8 largely to support library designers by enabling them to write more evolvable interfaces.


The Java designers decided to solve this problem once and for all by allowing
interface methods with concrete implementations (called default methods).


Those methods can be safely added to existing interfaces.


Now with help of default methods we you can just implement the methods in the interface.

Interfaces in Java 8 can now declare methods with implementation code; this

can happen in two ways.


a) Java 8 allows static methods inside interfaces.

b) Java 8introduces a new feature called default methods that allows you to provide a default

implementation for methods in an interface. In other words, interfaces can provide concrete

implementation for methods.

As a result, existing classes implementing an interface will automatically inherit the default implementations if they don’t provide one explicitly.

default methods in interface in java 8,default methods in interface example,java 8 interface default methods,default function in interface java,default function in interface,default and static methods in an interface,purpose of default method in interface,can we override default method of interface,java interface default methods diamond problem,default and static method in interface example,java8 new features,java8 default methods,

Post a Comment

0 Comments