DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Java
  4. Interface Default Methods in Java 8

Interface Default Methods in Java 8

Want to learn more about interface default methods in Java 8? Check out this tutorial to learn how using this new feature.

Muhammad Ali Khojaye user avatar by
Muhammad Ali Khojaye
CORE ·
Mar. 24, 14 · Tutorial
Like (33)
Save
Tweet
Share
508.22K Views

Join the DZone community and get the full member experience.

Join For Free

Java 8 introduces the “Default Method” or (Defender methods) feature, which allows the developer to add new methods to the interfaces without breaking their existing implementation. It provides the flexibility to allow interface to define implementation which will use as the default in a situation where a concrete class fails to provide an implementation for that method.

Let consider a small example to understand how it works:

?
public interface oldInterface {
    public void existingMethod();
        default public void newDefaultMethod() {
        System.out.println("New default method"
              " is added in interface");
    }
}

The following class will compile successfully in Java JDK 8:

public class oldInterfaceImpl implements oldInterface {
    public void existingMethod() {
        // existing implementation is here…
    }
}

If you create an instance of oldInterfaceImpl:?

oldInterfaceImpl obj = new oldInterfaceImpl ();
// print “New default method add in interface”
obj.newDefaultMethod(); 

Why the Default Method?

Reengineering an existing JDK framework is always very complex. Modifying one interface in a JDK framework breaks all classes that extend the interface, which means that adding any new method could break millions of lines of code. Therefore, default methods have introduced as a mechanism to extend interfaces in a backward-compatible way.

Default methods can be provided to an interface without affecting implementing classes as it includes an implementation. If each added method in an interface is defined with implementation, then no implementing class is affected. An implementing class can override the default implementation provided by the interface.

For Java 8, the JDK collections have been extended and the forEach method is added to the entire collection (which work in conjunction with lambdas). With the conventional way, the code looks like below:

?
public interface Iterable<T> {
    public void forEach(Consumer<? super T> consumer);
}

Since this result each implementing class with compile errors, a default method added with a required implementation in order that the existing implementation should not be changed.

The Iterable interface with the Default method is below:

?
public interface Iterable<T> {
public default void forEach(Consumer<? super T> consumer) {
    for (T t : this) {
        consumer.accept(t);
    }
}
}

The same mechanism has been used to adda  Stream in the JDK interface without breaking the implementing classes.

When to Use Default Method Over Abstract Classes

Abstract Classes Versus Interfaces in Java 8

After introducing Default Method, it seems that interfaces and abstract classes are the same. However, they are still a different concept in Java 8.

The abstract class can define constructors. They are more structured and can have a state associated with them. While in contrast, default method can be implemented only in the terms of invoking other interface methods, with no reference to a particular implementation's state. Hence, both are used for different purposes and choosing between two really depends on the scenario context.

Default Method and Multiple Inheritance Ambiguity Problems

Since Java classes can implement multiple interfaces and each interface can define a default method with the same method signature, the inherited methods can conflict with each other.

Consider the example below: 

?
public interface InterfaceA { 
    default void defaultMethod(){ 
        System.out.println("Interface A default method"); 
    } 
}

public interface InterfaceB {
    default void defaultMethod(){
        System.out.println("Interface B default method");
    }
}

public class Impl implements InterfaceA, InterfaceB  {
}

The above code will fail to compile with the following error:

java: class Impl inherits unrelated defaults for defaultMethod() from types InterfaceA and InterfaceB

In order to fix this class, we need to provide a default method implementation:

?
public class Impl implements InterfaceA, InterfaceB {
    public void defaultMethod(){
    }
}

Further, if we want to invoke default implementation provided by any super interface rather than our own implementation, we can do so as follows:

?
public class Impl implements InterfaceA, InterfaceB {
    public void defaultMethod(){
        // existing code here..
        InterfaceA.super.defaultMethod();
    }
}

We can choose any default implementation or both as part of our new method.

Difference Between Default Method and Regular Method

Default Method is different from the regular method in the sense that default method comes with default modifier. Additionally, methods in classes can use and modify method arguments as well as the fields of their class, but default method, on the other hand, can only access its arguments as interfaces do not have any state.

In summary, Default methods enable us to add new functionality to existing interfaces without breaking older implementation of these interfaces.

When we extend an interface that contains a default method, we can perform following,

  • Not override the default method and will inherit the default method.
  • Override the default method similar to other methods we override in subclass..
  • Redeclare default method as abstract, which force subclass to override it.

References

  • Interface evolution via virtual extension methods
  • What's New in JDK 8
Interface (computing) Java (programming language) Implementation

Published at DZone with permission of Muhammad Ali Khojaye, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Introduction to Container Orchestration
  • DevOps for Developers: Continuous Integration, GitHub Actions, and Sonar Cloud
  • NoSQL vs SQL: What, Where, and How
  • Solving the Kubernetes Security Puzzle

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: