Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
default
keyword
interfaces
methods

What are default methods in Java?

Educative Answers Team

The default keyword was introduced in Java 8 to solve compatibility issues. There were issues in Java’s earlier versions with interfaces only consisting of abstract methods, i.e., the method’s implementation was provided in a separate class. However, default brings up another issue.

Suppose an interface named Educative exists​ and the Courses class implements the interface. If the programmer wants to add a feature to the Educative interface along with its implementation, Java 8 will allow it.

Code

The code below explains the example mentioned above.

interface Educative 
{ 
    // abstract method 
    public void printCourse(int courseCode); 
  
    // default method 
    default void feature() 
    { 
      System.out.println("Default Method Executed"); 
    } 
} 
  
class Courses implements Educative 
{ 
    // implementation of square abstract method 
    public void printCourse(int courseCode) 
    { 
        System.out.println(courseCode); 
    } 
  
    public static void main(String args[]) 
    { 
        Courses programming = new Courses(); 
        programming.printCourse(101); 
        // default method called
        programming.feature();
    } 
} 

RELATED TAGS

java
default
keyword
interfaces
methods
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring