Java 8 – Default Methods

Posted on

Java-8

In my previous posts, we have discussed on Lambda Expressions in Java 8.  In this post we will discuss other cool features of Java 8 is Default methods.

Default methods enable you to add new functionality to the interfaces without breaking the class that implements that interface. It ensures that compatibility with code written for older versions of those interfaces.

A Default method is denoted by a keyword “default” by adding it before function access modifier. Also, an Interface or Functional Interface  can have one or more default methods.

default void method1(){

           // Default method body …..

}

According to “Open and Close” principle, which is also intended to open for extension but closed for modifications is stated that the design and writing of the code should be done in a way that new functionality should be added with minimum changes in the existing code. The design should be done in a way to allow the adding of new functionality as new classes, keeping as much as possible existing code unchanged.

Prior to Java 8, An interface can contain only abstracts methods and all classes that implement that Interface must be implemented all abstracts methods by the rule if any new functionalities need to be added into existing Interface that all implementor classes should be forced to implement the Interface’s methods. More likely it’s incompatible with code written for older versions of Interface then more efforts need to be required to change across the implementor classes.

By approaching default methods in Java 8, it can be fixed this issue by introducing the default methods in Interface. Default  methods do not force to override in subclasses, It is up to you either you can override or not.

Look at the below snippet code of Default Methods in Java 8.

Default method provides us a fixability to allow a method to be implemented in Interface. so Implementation may be used as default method  if a concrete class does not provide the implementation for that.


interface Calculable {
                // abstract method 
		int calc(int x, int y);
		// default method
		default void method(){
			System.out.println("hello");
		}
	}

In this snippet code example, calc() is an abstract method and method() is a default method which has been given the body. However, in this case,  Calculable is a Functional Interface.

Default methods in Multiple Inheritance :-

Since in Java, We can implement  multiple  inheritance  by using Interface but what happened if two or more Interfaces have  a default method with the  same signature then it’s causing a conflict in methods calls in implementor classes. Look at the below code, We have created two Interface i.e Executor & Runnable that have two methods respectively one is an abstract method and other is a default method that is exactly same as both Interface.

Here, MyClass is implemented both Interface Runnable & Executor then subsequently compiler reported a Compile time error i.e

“Duplicate default methods named getStatus with the parameters () and () are inherited from the types Runnable and Executor.”


package com.excerise1;

interface Executor {

	void execute();

	default void getStatus() {
		System.out.println("Ready to Execute.");
	}

}

interface Runnable {
	void run();

	default void getStatus() {
		System.out.println("Ready to Run.");
	}
}
/*
  COMPILER Errors:- Duplicate default methods named getStatus with the parameters () and () are inherited 
                    from the types Runnable and Executor
 */
public class MyClass implements Executor, Runnable {

	public static void main(String args[]) {
		MyClass o = new MyClass();
		o.getStatus();

	}

	@Override
	public void run() {
		// TODO Auto-generated method stub

	}

	@Override
	public void execute() {
		// TODO Auto-generated method stub

	}
}


In above code, Compiler force to override either one of default methods of Runnable or Executor Interface, Otherwise Compiler will not know what default method to used at a time.

In order to workaround solution, we implement default method in subclass i.e MyClass therefore it’s overriding both methods of Runnable & Executor Interface.


public class MyClass implements Executor, Runnable {

	public static void main(String args[]) {
		MyClass o = new MyClass();
		o.getStatus();

	}

	@Override
	public void run() {
		// TODO Auto-generated method stub

	}

	@Override
	public void execute() {
		// TODO Auto-generated method stub

	}

	@Override
	public void getStatus() {
		
	}
}


In the above code, getStatus() methods has a dummpy body or own definitation but if you want to invoke one of either Runnable or Executor default methods then we do it as following ways:-


        @Override
	public void getStatus() {
		Runnable.super.getStatus();
	}
   // OR
	/*@Override
	public void getStatus() {
		Executor.super.getStatus();
	}*/

Thanks
——-

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