Let me introduce you to the default methods in Java 8. They are really new and surprising. The default methods are the methods in the interface for which the default body is provided. Usually, interfaces contains only abstract methods and when a class implement any interface it must provide the body for all the methods in the interface. This might seem difficult for the writers of classes. Though they don't know what to write in the methods that they don't wish to implement, they simply have to open and close the curly braces which indicates that the body has been provided. So if an interface contains 100 methods and you have a written a class implementing that interface, you need to provide the body to all the methods which is difficult. As a result, we've actually followed the concept of Adapter classes in event handling of AWT and Swing. Thinking in an entirely new way, the Java developers have introduced the default methods.
The default methods have a default body. The code in this body is executed when the method is called. While this seems to violate the rules of an interface, it has been a feature that might be helpful. This default code is replaced when the method is overrided in the implementing class. The following example illustrates default methods.
The default methods have a default body. The code in this body is executed when the method is called. While this seems to violate the rules of an interface, it has been a feature that might be helpful. This default code is replaced when the method is overrided in the implementing class. The following example illustrates default methods.
interface MyInterface
{
public abstract void A();
default public void B(){System.out.println("B");}
}
class MyInterfaceImpl implements MyInterface
{
public static void main(String args[])
{
MyInterfaceImpl m=new MyInterfaceImpl();
m.A();
m.B();
}
public void A()
{
System.out.println("A");
}
}
Output
A
B
Notes
In the above program 'A' is a normal method in the interface
MyInterface
. No default body is provided for this in the interface. MyInterfaceImpl
class implements MyInterface
and hence it has to provide the body for 'A' method. Unlike A method the B method need not be implemented in the class because it is a default method and a default body has been present for it. The default body is executed when the method B is not implemented (otherwise overrided) in the class.Try it yourself, overriding the B method in the class and write a statement of your own in that method. What happens when you call B? The 'B' which you have overrided will be executed but not the default B. This is a Java 8 feature.