Wednesday, May 9, 2012

An Abstract Class implements an interface

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.

Question:
A curious thing happens in Java when you use an abstract class to implement an interface: some of the interface's methods can be completely missing (i.e. neither an abstract declaration or an actual implementation is present), but the compiler does not complain.
For example, given the interface:
public interface IAnything {
  void m1();
  void m2();
  void m3();
}
the following abstract class gets merrily compiled without a warning or an error:
public abstract class AbstractThing implements IAnything {
  public void m1() {}
  public void m3() {}
}

Answer:
 
This is considered a good practice - here is an example from the FCL itself.
The reason this can be a good thing is that the abstract class becomes a implementation helper for anyone who wants to do the actual implementation. Comparer<T> is a good example of just this concept.


No comments:

Post a Comment

Blog Archive