Java 8 – Default Methods in Interface

Java 8 arrived with new features and advances which has also interface with default methods in its arsenal too.

What we might have heard about default methods in interfaces?

  • Multiple inheritance.
  • Backward Compatibility.
  • Default methods reduces the need of abstract class.

While the first two points are correct but the last point is not though it seems to more or less works like the abstract class. I will keep it for last, and starts with some basic information.

Why we needed Default Methods inside Interface?

As it is said, when there are problems we look around for solutions , this is the case where it get fits. Think of a situation where one needs to declare a new method signature inside an interface, and that interface has been implemented in 100’s of classes.  Hhhuh!! That is a painful task as first it is mandatory to  implement it all the the new method in 100 instances and also we need to handle the situation where we don’t need that function.

What if we are allowed to write a default method definition inside interface?
Listen behind, someone whispering “Java 8 allows you to do so…

Yes, with Java 8, you can define a default method inside interface and use it in the implementing class and this is not mandatory. Let’s look how?

package com.sovanm.java8;
/**
 * @author sovanm
 * This is the first Interface having two declaration and a default method. 
 */
public interface DefaultInterfaceFirst {
	/**
	 * Interface Declaration for first interface
	 */
	void onlyMethSignature();
	void onlyMethSignature2();
	/**
	 * Default Interface to calculate sum of 2 numbers
	 */
	default int  defaultInterfaceSum(int i1, int i2){
	        System.out.println("Sum method from First Interface");
		return i1 + i2;
	}
}

This is an example of interface with default methods and in implementing class this can be used as “DefaultInterfaceFirst.defaultInterfaceSum(10, 20);”.

As we have rules everywhere, here too we have few

  1. If an implementing class overrides a default method and provides its own functionalities then it has precedence over the interface’s default.
  2. When a class implements more than one interface and each interface has same default methods (may or may not with same definition) with same signature, then it has to be overridden in the class. Otherwise JVM will raise compile time exception.
  3. In case of multilevel inheritance of interface, the child default method will take precedence. Suppose B extends A and both have same default method, then B’s method will take precedence.

We have to follow these set of rules while designing out default methods in interfaces.

What if, We want to use the interface’s default method in case of multiple implementation of interface ?

As stated above, when we implement multiple interfaces with same default method, we have to override the method in the implementing class. Suppose we want to access the default method of one of the interface then how we can do that?

Java is “super” fun! 

For this Java has provided “super”. We can use super of each interface and access the default method.

Example.

@Override
public int defaultInterfaceSum(int i1, int i2) {
		
		// This calls the default method from first interface
		int firstDefaultMethod = DefaultInterfaceFirst.super
                                                  .defaultInterfaceSum(i1, i2);
		// This calls the default method from second interface
		int secondDefaultMethod = DefaultInterfaceSecond.super
                                                  .defaultInterfaceSum(24,45);
		return firstDefaultMethod;
	}

Isn’t it super?

Is Abstract Class replaced By Default Methods?

At these point, you might be thinking, if we have default interface methods, then why should we use Abstract classes any more? Wait, they differs…

Abstract class can have attributes and can be constructed via the child class super() where as Interfaces with or without default methods can not be constructed in any class and also can not have any attributes. These  are still those contracts.

Why are they introduces ?

To eradicate the problem with interfaces. Not with default methods, we can change a interface as we want and we do not have to implement those methods in all classes. If we need to do so, we can otherwise we can use where ever required without changing the codes. Now it is a win win situation while re-engineering interfaces provides and backward compatibility.

Play around with Java 8 features, you will need time to get accustomed. Please have a look at the github project with a simple demo of default method.

Till next time…
Happy coding 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s