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

  • Building a Rust Command Line Interface to Chat With Llama 3.2
  • A Beginner’s Guide to GraphQL Interfaces and Unions
  • Contexts in Go: A Comprehensive Guide
  • The Power of Refactoring: Extracting Interfaces for Flexible Code

Trending

  • Performing and Managing Incremental Backups Using pg_basebackup in PostgreSQL 17
  • MySQL to PostgreSQL Database Migration: A Practical Case Study
  • Integration Isn’t a Task — It’s an Architectural Discipline
  • Why High-Performance AI/ML Is Essential in Modern Cybersecurity

Default and Static Methods in Interfaces

This overview of both default and static methods covers why default methods are necessary with interfaces and how they interact with inheritance and multiple inheritance.

By 
Gaurav Rai Mazra user avatar
Gaurav Rai Mazra
·
Updated Feb. 09, 17 · Tutorial
Likes (26)
Comment
Save
Tweet
Share
49.4K Views

Join the DZone community and get the full member experience.

Join For Free

Java 8 introduced default and static methods in interfaces. This feature enables us to add new functionality in the interfaces without breaking the existing contract of the implementing classes.

How to Define Default and Static Methods?

Default methods have default, and static methods have thestatic keyword in the method signature.

public interface Parser {
  List<String> parse(File file);

  // default implementation valid for all the file parser viz. JsonFileParser, CsvFileParser, TextFileParser
  default boolean canParse(File file) {
    return Objects.nonNull(file) && file.getName().endsWith(getFileType().getExtension());
  }

  FileType getFileType();

  static void someStaticHelperMethod() {
    //helper method implementation 
  }
}

What Is the Need for Default Methods?

Default methods in interfaces help us to introduce new functionality without breaking the contract of the implementing classes.

Suppose we have an Expression interface that has ConstantExpression, BinaryExpression, DivisionExpression etc. as existing implementations. Now we get a requirement to add new functionality.

  • Return the signum of the evaluated result.

  • Return signum after evaluating the expression.

This can be done with default and static methods without breaking any functionality as follows.

public interface Expression {
  double evaluate();

  default double signum() {
    return signum(evaluate());
  }

  static double signum(double value) {
    return Math.signum(value);
  }
}


You can find the full example code on GitHub.

Default Methods and Multiple Inheritance Ambiguity Problems

Java supports multiple inheritance of interfaces. Consider having two interfaces, InterfaceA and InterfaceB , having default methods with the same signature. Your class ConcreteC is implementing both the interfaces.

interface InterfaceA {
  void performA();
  default boolean canPerform() {
    // return true if I can perform the action
  }
}

interface InterfaceB {
  void performB();
  default boolean canPerform() {
    //return true if I can perform the action
  }
}

class ConcreteC implements InterfaceA, InterfaceB {

}


The above code will fail to compile with "error: unrelated defaults for canPerform()from InterfaceA and InterfaceB."

To overcome this problem, you need to override the default method.

class ConcreteC implements InterfaceA, InterfaceB {
  override
  public boolean canPerform() {

  }
}


But say you don't want to provide the implementation of the overridden default method but instead want to reuse the existing one. That is also possible with the following syntax.

class ConcreteC implements InterfaceA, InterfaceB {
  override
  public boolean canPerform() {
    return InterfaceA.super.canPerform();
  }
}

A Few Important Points for Default Methods

  • You can inherit the default method.

  • You can redeclare the default method essentially making it abstract.

  • You can redefine the default method (equivalent to overriding).

Interface (computing)

Opinions expressed by DZone contributors are their own.

Related

  • Building a Rust Command Line Interface to Chat With Llama 3.2
  • A Beginner’s Guide to GraphQL Interfaces and Unions
  • Contexts in Go: A Comprehensive Guide
  • The Power of Refactoring: Extracting Interfaces for Flexible Code

Partner Resources

×

Comments

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: