Wednesday, April 5, 2017

Default and Static methods in Java8

Java 8 introduces a new concept of default and static method implementation in interfaces. Before Java 8, interfaces could have only abstract methods but now It allows the interfaces to have methods with implementation without affecting the classes that implement the interface and provides backward comparability so that existing interfaces can use the lambda expressions without implementing the methods in the implementation class.

Eg: Now List or Collection has forEach method declaration which is only possible because of default declaration. 

Default Method:

The default methods are also known as defender methods or virtual extension methods and are defined inside the interface and tagged with default. These methods are non-abstract methods.

What about Multiple Inheritance?

As we know adding method definitions in interfaces can add ambiguity in multiple Inheritance and if a java class implement multiple interfaces and each interface can define default method with same method signature, then the inherited methods can conflict with each other.
Let’s create another interface with same default method, in below image you can see that AnotherInterface also has default method multiply.

Java 8 handle this issue at Compile type as it will result in a compilation error and can be resolved by overriding the default method or by implementing class should explicitly specify which default method is to be used.

Static Method:

An interface can also have static helper methods from Java 8 onwards and it is similar to default method except that we can’t override them in the implementation classes.

Difference between default methods and abstract class

·         Abstract class can hold state of an object. It can have constructors and member variables.
·         interfaces with Java 8 default methods cannot hold state. It cannot have constructors and member variables.
·         You should still use Abstract class whenever you think your class can have state or you need to do something in a constructor.
·         Default method should be used for backward compatibility. Whenever you want to add additional functionality in an existing legacy interface you can use default methods without breaking any existing implementor classes. 
      You can download the source code from GitHub.
Happy Learning!!