Default Method and Static Method in Interface
Java 8 has introduced one new feature called default method. With this feature, the old definition of interfaces has changed. Earlier, java didn’t allow concrete methods in interfaces. But now, with java 8, it is possible.
Interfaces can have concrete methods now. Such methods are called default methods. Let’s see one example
package com.javatrainingschool;
public interface DefaultMethodInterface {
void display();
//default method which has definition
default void displayDefaultMessage() {
System.out.println("This is default message.");
}
}
package com.javatrainingschool;
public class DefaultMethodExample implements DefaultMethodInterface {
public void display() {
System.out.println("This is display method.");
}
public static void main(String[] args) {
DefaultMethodInterface obj = new DefaultMethodExample();
obj.displayDefaultMessage();
}
}
Output :
This is default message.
Overriding Interface Default Method
We can also override default method in implementing class. In such cases, overridden behvaiour takes place.
package com.javatrainingschool;
public class DefaultMethodExample implements DefaultMethodInterface {
public void display() {
System.out.println("This is display method.");
}
public void displayDefaultMessage() {
System.out.println("This is overridden default method.");
}
public static void main(String[] args) {
DefaultMethodInterface obj = new DefaultMethodExample();
obj.displayDefaultMessage();
}
}
Output :
This is overridden default method.
Static Methods
Now, with java 8, we can also define static methods in interfaces. These methods are concrete in nature. Now, it is obvious to ask, what is the need of static methods when we already have default methods.
Answer is that default methods can be overridden by implementing classes. But suppose, if we want some default behaviour of interface not to be overridden, then we can define such behaviour as static. Let’s see one example
package com.javatrainingschool;
public interface DefaultMethodInterface {
void display();
//default method which has definition
default void displayDefaultMessage() {
System.out.println("This is default message.");
}
static void displayStaticMessage () {
System.out.println("This is static message of the inerface.");
}
}
Implementing class :
package com.javatrainingschool;
public class DefaultMethodExample implements DefaultMethodInterface {
public void display() {
System.out.println("This is display method.");
}
public void displayDefaultMessage() {
System.out.println("This is overridden default method.");
}
public static void main(String[] args) {
DefaultMethodInterface obj = new DefaultMethodExample();
obj.displayDefaultMessage();
DefaultMethodInterface.displayStaticMessage();
}
}
Output :
This is overridden default method.
This is static message of the inerface.