Admin

Default method in java 8

Till Java 7, we have learned a lot of things about interfaces. All those things have been in our mind whenever we have written code or designed applications. Some of these concepts are going to change drastically from Java 8 onward, after introduction of default method in java.

First of all, from Java 8 we can have method implementations in interface called as Default methods in contrast to Java 7.

What is default method in java?

Default method in java is the default implementation of method. This methods will work as method implementation if implementing class doesn’t override or satisfy default behavior of method.

It is not mandatory to override the default method in implementing class

This feature therefore helps us in extending interfaces with additional methods, without requiring to change the existing implementing classes, which until Java 7 used to break the functionality.

public interface Interface1 {

default void print(String string){

System.out.println(“Printing in interface : “+ string);

}

}

Difference Between Default and Regular Method

Default MethodRegular Method
Comes with “default” modifierUnlike default methods, these cannot have “default” modifier
Cannot access class variablesCan access class variables

When we extend an interface that contains a default method, we can perform following

  • Not override the default method and will inherit the default method.
  • Override the default method similar to other methods we override in subclass.
  • Re declare default method as abstract, which consequently forces the subclass to override it.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.