An Interface cannot have Non-Abstract Methods.. Really ? Check Extension Methods in Java…

Hello Friends,

Java 8 enables us to add non-abstract method implementations to interfaces by utilizing the “default" keyword. This feature is also known as Extension Methods.Here is the example,

interface MyInterface {
// Abstract Method
String enter(String name);

// Non-Abstract Method by using "default" Keyword
default String exit(String name) {
return "Hello " + name +", you are using exit method of MyInterface interface";
}
}
public class MyClass{

public static void main(String[] args) {

// we are implementing MyInterface interface as an anonymous object
//and overridding abstract method
MyInterface f1 = new MyInterface() {

@Override
public String enter(String name) {
return "Hello " + name +", you are using enter method of MyInterface interface";
}
};

// calling both abstract as well as non-abstract methods of interface
System.out.println(f1.enter("Aman"));
System.out.println(f1.exit("Aman"));

}
}

Output is :

Hello Aman, you are using enter method of MyInterface interface
Hello Aman, you are using exit method of MyInterface interface

Advertisements

One thought on “An Interface cannot have Non-Abstract Methods.. Really ? Check Extension Methods in Java…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s