Stats

610 Contributors: 16 Tuesday, May 2, 2017
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap
Download eBook

Default Methods

Download java eBook

Introduction

Default Method introduced in Java 8, allows developers to add new methods to an interface without breaking the existing implementations of this interface. It provides flexibility to allow the interface to define an implementation which will be used as default when a class which implements that interface fails to provide an implementation of that method.

Syntax

  • public default void methodName() {/* method body */}

Remarks

Default methods

  • Can be used within an interface, to introduce a behaviour without forcing existing subclasses to implement it.
  • Can be overridden by subclasses or by a sub-interface.
  • Are not allowed to override methods in java.lang.Object class.
  • If a class implementing more than one interface, inherits default methods with identical method signatures from each of the intefaces, then it must override and provide its own interface as if they were not default methods (as part of resolving multiple inheritance).
  • Although are intended to introduce a behaviour without breaking existing implementations, existing subclasses with a static method with same method signature as the newly introduced default method will still be broken. However this is true even in case of introducing an instance method in a superclass.



Static methods

  • Can be used within an interface, primarily intended to be used as a utility method for default methods.
  • Cannot be overridden by subclasses or by a sub-interface (is hidden to them). However as is the case with static methods even now, each class or interface can have its own.
  • Are not allowed to override instance methods in java.lang.Object class (as is presently the case for subclasses as well).



Below is a table summarizing the interaction between sub-class and super-class.

-SUPER_CLASS-INSTANCE-METHODSUPER_CLASS-STATIC-METHOD
SUB_CLASS-INSTANCE-METHODoverridesgenerates-compiletime-error
SUB_CLASS-STATIC-METHODgenerates-compiletime-errorhides



Below is a table summarizing the interaction between interface and implementing-class.

-INTERFACE-DEFAULT-METHODINTERFACE-STATIC-METHOD
IMPL_CLASS-INSTANCE-METHODoverrideshides
IMPL_CLASS-STATIC-METHODgenerates-compiletime-errorhides

References :

  • http://www.journaldev.com/2752/java-8-interface-changes-static-method-default-method
  • https://docs.oracle.com/javase/tutorial/java/IandI/override.html

Related Examples