Saturday 11 August 2012

Java Abstract Class vs Interface Pros and Con's

This a quick reminder about pros and con's of Java abstract classes and interfaces:

Interface

  • A class can implement multiple interfaces
  • An interface cannot provide any code at all
  • An interface can only define public static final constants
  • An interface cannot define instance variables
  • Adding a new method has ripple effects on implementing classes (design maintenance)
  • JAXB cannot deal with interfaces
  • An interface cannot extends or implement an abstract class
  • All interface methods are public
In general, interfaces should be used to define contracts (what is to be achieved, not how to achieve it).

Abstract Class

  • A class can extend at most one abstract class
  • An abstract class can contain code
  • An abstract class can define both static and instance constants (final)
  • An abstract class can define instance variables
  • Modification of existing abstract class code has ripple effects on extending classes (implementation maintenance)
  • Adding a new method to an abstract class has no ripple effect on extending classes
  • An abstract class can implement an interface
  • Abstract classes can implement private and protected methods
Abstract classes should be used for (partial) implementation. They can be a mean to restrain the way API contracts should be implemented.

6 comments:

  1. Nice post. I found one error under the Abstract class section:

    An interface can define instance variables.

    ReplyDelete
    Replies
    1. No you can't, all variables are declared static final in an interface, no matter if the modifiers are there or not. Try to run a program modifying such a variable, the code will not compile.

      Delete
    2. check yo:
      Abstract Class

      A class can extend at most one abstract class
      An abstract class can contain code
      An abstract class can define both static and instance constants (final)
      >>>> An interface can define instance variables

      Delete
    3. nope by default instance varible are static final in interface

      Delete
  2. What he is saying is that you actually wrote that as the 4th item of the abstract class description.

    ReplyDelete