Before beginning this post, I would like state that this post assumes some knowledge of Java.
Prior to Java 8, all methods in an interface had to be ‘abstract’. However, in Java 8, default and static methods could also be defined in interfaces. These are discussed in the following sections.
Default Methods:
A default method in an interface is used to define the ‘default’ behaviour of an object of that interface type, in case a class implementing that interface does not override the method. Unlike other interface methods, default methods have a method body. A default method is declared using the keyword ‘default’:
interface TestInterface {
default void defaultMethod() { Â } Â Â Â //a default method
}
Note that the above method uses curly braces, not a semicolon. Just like normal methods, statements can be included between the curly braces. Now consider another piece of code:
package bala;
interface TestInterface{
default void print(){
System.out.println(“Default”);
}
}
class Sample1 implements TestInterface{ //overrides print()
public void print(){
System.out.println(“Not Default”);
}
}
class Sample2 implements TestInterface{} //doesn’t override
public class Test {
public static void main(String[] args) {
TestInterface obj1 = new Sample1();
TestInterface obj2 = new Sample2();
obj1.print();
obj2.print();
}
}
The above code prints:
Not Default
Default
In the above code, both the classes, Sample1 and Sample2, implement the interface TestInterface, which contains a default method.
class Sample1 overrides the print() method but Sample2 doesn’t.  In the main() method, two objects of object types Sample1 and Sample2 are created, which then invoke the print() method. Since Sample1 has the overridden print() method, the code in the overridden version executes.
But the print() method is not overridden in Sample2, Â so the code in the default method of TestInterface executes. This accounts for the above output.
Static Methods:
Recall the definition of static methods – they belong to the class rather to an instance of the class.
As in classes, static methods in interfaces are the methods that can be called using the interface name itself, rather than using an object reference variable. These methods also use curly braces. Their usage is very similar to the usage of static methods in classes, as demonstrated in the following code:
package bala1;
interface TestInterface2{
static void print(){
System.out.println(“Static method inside an interface”);
}
}
public class Test2 {
public static void main(String[] args) {
TestInterface2.print();
}
}
As expected, the above code prints:
Static method inside an interface
We have seen the newer features of Java 8(namely – default and static methods in interfaces) in this post! Join me as I uncover some more technical aspects of the world!