For a while I have been puzzled as to why we need default methods in Interfaces, and today I was reading about it. Even though few of my questions are answered, I still have a few queries.
Let's take a simple example, I've an interface1. Class A and class B implement interface1. interface1 has a method X.
interface interface1{
void methodX();
}
class A implements interface1{
@override
public void methodX(){
//something
};
}
class B implements interface1{
@override
public void methodX(){
//something
};
}
From what I understood, since adding a new method Y to interface1, would have broken Class A and class B, default methods were introduced. This means that now I can add a default method, without the need for modifying Class A and Class B. This also means that the default method has to be generic enough to do whatever we expect it to do, for both class A and class B.
Now, let's consider that we normally add functions in interface so that we can provide a class specific implementation to them by overriding it. So basically, if I am adding a method Y in an interface as default, then I will expect class A and class B (or class A/ClassB) to override the method.
Which means, I will be modifying Class A/Class B or both.
This is what confuses me. This could have been handled by creating a new interface and modifying 1 (or both) class(es) to implement that new interface (interface 2 extending interface1), and then provide implementation for the same in the class.
interface interface2 extends interface1{
void methodY();
}
class A implements interface2{
@override
public void methodY(){
//something
}
}
class B implements interface1{
@override
public void methodX(){
//something
};
}
How does default method, actually help us in not modifying the classes which implements it.