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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
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

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Advanced Brain-Computer Interfaces With Java
  • Simplify Java: Reducing Unnecessary Layers and Interfaces [Video]
  • Java 21 SequenceCollection: Unleash the Power of Ordered Collections
  • Projections/DTOs in Spring Data R2DBC

Trending

  • Concourse CI/CD Pipeline: Webhook Triggers
  • Blue Skies Ahead: An AI Case Study on LLM Use for a Graph Theory Related Application
  • Cookies Revisited: A Networking Solution for Third-Party Cookies
  • Immutable Secrets Management: A Zero-Trust Approach to Sensitive Data in Containers
  1. DZone
  2. Coding
  3. Java
  4. Interface Enhancement in Java 8

Interface Enhancement in Java 8

Interfaces have seen massive improvements since they were first brought out. Combined with method definitions, you've got a lot of flexibility on your hands.

By 
Arun Pandey user avatar
Arun Pandey
DZone Core CORE ·
Feb. 23, 17 · Tutorial
Likes (23)
Comment
Save
Tweet
Share
54.5K Views

Join the DZone community and get the full member experience.

Join For Free

Interface was meant to define a contract before Java 8, where we were able to define the methods a class needed to implement if binding himself with the interface. Interface was only involved with abstract methods and constants.

But in Java 8, Interface has become much more, and now it can have methods defined using static or default. Remember that default methods can be overridden, while static methods cannot.

Method Definitions

Interface was meant for good designers because when we create an Interface, we should know the possible contract that every class should implement. Once your contract definition is done and classes have implemented the contract, it's difficult to change the definition of an Interface, as it will break the implemented classes.

A good designer always creates an interface and provides a base class, which provides the default definition of the Interface methods, and classes should extend the base class in place of implementing the interface directly. In this way, any future change in Interface could be taken care of by the base class. Other implementations of sub-classes would be fine.

In Java 8, they tried to fix this issue by providing method definitions — using static or default. We can add the definitions using static or default in Interface without breaking the existing classes, making it easier to design interfaces in Java 8.

Do We Still Need Abstract Classes?

After the Java 8 interface enhancements, the new version of Interface looks like a great replacement for the Abstract class, right? No, not at all. There are still the differences between these two. Do you remember 'access specifiers' (public, protected, etc.)?

So the Abstract class can have any of these access specifiers for their methods and variables while an Interface is always public and variables in an Interface are always constants. So we need to be very wise when choosing between the Interface and Abstract classes, and I believe that some intelligence is still required.

Examples of Interface Enhancements

We can define an Interface as having static and default methods as below:

Java8Interface.java:

package com.test.interfac.enhancement;

/**
 * @author arun.pandey
 */
public interface Java8Interface {

    //defaults method - by default it's public
    default void hi() {
        System.out.println("In Java8Interface: new feature of Java8 is saying Hi....");
    }

    //static method - by default it's public
    static void hello() {
        System.out.println("In Java8Interface: new feature of Java8 is saying Hello....");
    }
}


The concrete class that is implementing the above Interface can be used as below.

ConcreteClass.java:

package com.test.interfac.enhancement;

/**
 * @author arun.pandey
 */
public class ConcreteClass implements Java8Interface {

    public static void main(String[] args) {
        ConcreteClass c = new ConcreteClass();
        c.hi(); // would be accessible using class instance

        //Not possible to call using class instance
        Java8Interface.hello();
    }
}


Which will lead to this output:

In Java8Interface: new feature of Java8 is saying Hi....
In Java8Interface: new feature of Java8 is saying Hello....


But suppose you have two interfaces with the same method signature as 'default'. Then, your class should define the implementation for that method. Otherwise, you'll see a compile time error.

Let's see how that plays out below. The following Interface has the same methods as our Java8Interface.

Java8Interface_1.java:

package com.test.interfac.enhancement;

/**
 * @author arun.pandey
 */
public interface Java8Interface_1 {
    default void hi() {
        System.out.println("In Java8Interface_1: new feature of Java8 is saying Hi....");
    }

    static void hello() {
        System.out.println("In Java8Interface_1: new feature of Java8 is saying Hello....");
    }
}


Meanwhile, our concrete class handles the implementation for our default method as follows:

ConcreteClass.java:

package com.test.interfac.enhancement;

/**
 * @author arun.pandey
 */
public class ConcreteClass implements Java8Interface, Java8Interface_1 {

    public static void main(String[] args) {
        ConcreteClass c = new ConcreteClass();
        c.hi();
        Java8Interface.hello();
    }

    //We need to override hi method otherwise compilation error
    @Override
    public void hi() {
        Java8Interface.super.hi();
    }
}


And our output will be as follows:

In Java8Interface: new feature of Java8 is saying Hi....
In Java8Interface: new feature of Java8 is saying Hello....


Next, say a List API has the same default implementation as below: 

default void sort(Comparator c))

That helps call the sort methods on our List, and no more Collections API is needed.

And let's see the snippet for calling the sort method using a List API:

List list = new ArrayList<>(); list.add("v");
list.add("a");

list.add("z"); list.add("d");

list.sort((val1, val2) -> val1.compareTo(val2));


Enjoy the power of Interface. Happy learning!

Interface (computing) Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Advanced Brain-Computer Interfaces With Java
  • Simplify Java: Reducing Unnecessary Layers and Interfaces [Video]
  • Java 21 SequenceCollection: Unleash the Power of Ordered Collections
  • Projections/DTOs in Spring Data R2DBC

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!