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.
The code below explains the example mentioned above.
interface Educative{// abstract methodpublic void printCourse(int courseCode);// default methoddefault void feature(){System.out.println("Default Method Executed");}}class Courses implements Educative{// implementation of square abstract methodpublic void printCourse(int courseCode){System.out.println(courseCode);}public static void main(String args[]){Courses programming = new Courses();programming.printCourse(101);// default method calledprogramming.feature();}}