Monday 19 February 2018

Java 8 Default Method Interface

(Download One Minute Java Mobile App for Latest Updates)

Introduction

Prior to Java SE 8, interfaces were expected to have abstract methods only and the classes implementing the interfaces had to override all those abstract methods. But Java SE 8 has made it possible to hold method definitions in an interface using Default methods.
Default Methods can be used to introduce new functionalities into interfaces without breaking the existing classes which implement those interfaces. The Default methods provide their own definitions, so there is no compulsion on implementing classes to override default methods.

Syntax


  public interface firstDefaultTest
 {
  default void test()
  {
   System.out.println("This is a default method with default keyword");
  }
 }

Things to know

  • A default method cannot override methods from java.lang.Object
  • An interface can also have a static default method from Java 8
  • There are chances that 2 different interfaces may have default method with same name and signature and a class might implement both the interfaces, which causes ambiguity.
    • One way is to override the default method in implementing class
    • Other way is to override default method and invoke default method of the required interface with super keyword ex: interfaceName.super.methodName()
  • Default methods help to remove base implementation classes. The default implementations can be provided in the interface and the implementating classes can choose which one to override.

No comments:

Post a Comment