I am reading the book -- Hadoop: The Definitive Guide
In chapter 2 (Page 25), it is mentioned "The new API favors abstract class over interfaces, since these are easier to evolve. For example, you can add a method (with a default implementation) to an abstract class without breaking old implementations of the class". What does it mean (especially what means "breaking old implementations of the class")? Appreciate if anyone could show me a sample why from this perspective abstract class is better than interface?
thanks in advance, George
In the case of an interface, all methods that are defined in an interface must be implemented by a class that implements it.
Given the interface A
interface A {
public void foo();
}
and a class B:
class B implements A {
}
it has to provide an implementation for the method defined in the interface:
class B implements A {
@Override
public void foo() {
System.out.println("foo");
}
}
Otherwise it's a compile-time error. Now take an abstract class with a default implementation of a method:
abstract class C {
public void bar() {
System.out.println("bar");
}
}
where a class inheriting from this abstract class can look like this:
class D extends C { }
without an error. But it can also override the default method implementation if it's inclined to do so.
What the author was saying there: If your API isn't stable yet and you need to adapt interfaces (yes, abstract classes are also interfaces (in OOP-speak)), then an abstract class allows you to add things without breaking classes that are already there. However, this only holds true for non-abstract methods. If you add abstract methods, then they still need to be implemented in every derived class. But still, it can make your life easier if you have an API that is still evolving and already lots of stuff building on it.
If you add a method with a default implementation to an abstract class, nothing needs to change in any derived classes.
Alternatively, if you add a method to an interface, any classes implementing that interface need to implement the method - otherwise they will not compile.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With