In Java when you add a new method to an interface, you break all your clients. When you have an abstract class, you can add a new method and provide a default implementation in it. All the clients will continue to work.
I wonder why the interface is designed this way?
All the old methods are still there, so seems like there is no backward compatibility issue. (Of course there need to be certain exceptions, but I think enabling to add new methods to java interfaces without breaking the clients could be really good idea...)
I'd appreciate your comments.
There are a few possible breaks I can see
IMHO, It's the subtle problems which are more likely to cause you grief. However, I wouldn't assume that simply adding a method will break the code and I wouldn't assume that if a client's code isn't getting runtime error means they are using the latest version of anything. ;)
If I compile this code
public interface MyInterface {
void method1();
// void method2();
}
public class Main implements MyInterface {
@Override
public void method1() {
System.out.println("method1 called");
}
public static void main(String... args) {
new Main().method1();
}
}
it prints
method1 called
I then uncomment method2() and recompile just the interface. This means the interface has a method the Main
doesn't implement. Yet when I run it without recompiling Main
I get
method1 called
If I have
public class Main implements MyInterface {
public void method1() {
System.out.println("method1 called");
}
public void method2() {
System.out.println("method2 called");
}
public static void main(String... args) {
new Main().method1();
}
}
and I run with // method2()
commented out, I don't have a problem.