Posts

Showing posts with the label Default Interface Methods

Java 8 Default Interface methods explained

One of the new features provided by Java 8 is the support for default methods in interfaces. In this blog post, I will be explaining Java 8 default interface methods in detail. I will be covering what default methods are, how they work and why they were added. Edit What are default interface methods? Default methods are methods in an interface that have method bodies, They are specified with the  keyword “ default “. How do default interface methods work? Prior to Java 8, interfaces could not have method bodies.  So consider the following code snippet: public interface MyInterface {public void methodA();public void methodB(){System.out.println("In methodB");}}   This code causes a compilation error. This is because methodB has a method body.  However, if you are using Java 8, you can change the code as follows: public interface MyInterface {public void methodA();default public void methodB(){System.out.println("In methodB");}} So now, the def...