What are default methods in Java?

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();
}
}
Copyright ©2024 Educative, Inc. All rights reserved