Sunday, October 11, 2015

Default Methods in Java

Default Method is one of the features of Java 8. Default Method is
  • A method - which has a keyword default before it
  • Has to be defined only in Interface
  • Must be implementation. 
  • Can be overridden in Implemented Classes but has to be defined without default keyword.
  • An Interface can have multiple default methods
Default method may break the contract of an Interface because technically interface should consists of all abstract methods and no implementations. The main reason behind the concept of default method is to add steam method to collections (especially to interface) without breaking the implementation classes.

Example

  • As mentioned earlier, default method is a method with implementation in an Interface
public interface AInterface 
{
    public default void print()
    {
        System.out.println("Default Method in Interface A");
    }
}
  • If a class implements it, then it may or may not override the default method along with it's own methods.
public class AImplementation implements AInterface
{
    public void otherMethod()
    {
        System.out.println("New Method Defined in AImplementation");
    }
}
  • Calling a default is same as like other methods as below
AImplementation a = new AImplementation();
a.print();
a.otherMethod();
  • As multiple interfaces can be implemented by one class, but there is a probability of same default method with the same name, defined in both interfaces. Let's say another interface with a default method print like below
public interface BInterface
{
    default void print()
    {
        System.out.println("Default Method in Interface B"); 
    }
}
  • Now, if a class implements both AInterface and BInterface, which has same default method print, then compiler throws an error saying "Duplicate default methods named print with the parameters () and () are inherited from the types BInterface and AInterface". So, print method has to be overridden in the implemented Class like below
public class CImplementation implements AInterface, BInterface
{
    @Override
    public void print()
    {
        System.out.println("Default Method in Interface A");
    }
}

More details on the default methods and its use in Java will be explained in the next post.

Happy Learning!!!!

No comments:

Post a Comment