Popular Feed

Why Java8 introduced Default methods

Problem before Java 8.

Before Java 8, we implement an interface as below.

interface Testdefault{

void printInLoop(); }

class TestInt implements Testdefault { void printInLoop(){ for (String s:listData) { System.out.println(s); } } }

So let us say I want to add a new method in Testdefault Interface.

interface Testdefault{

void printInLoop();

        void xyz();

}

So after adding the above method in interface my TestInt class will give me a compilation error. Because the newly method is not implemented yet.

So to resolve that issue I have to change the entire code base where I have implemented this interface.


After Java 8.

Java 8 provides the features to add default methods in the interface which are not required to implement.

interface Testdefault{
	void xyz();
	default void printInLoop(List<String> listData) {
		for (String s:listData) {
			System.out.println(s);
		}
	}
}

So after adding the above method to the interface, the class will not give any compilation error.

So we can say that you can use your old code and new functionalities also without breaking it.

So in conclusion we can say that default methods provide us backward compatibility.

we can create any number of default methods.


No comments: