Monday, 25 July 2011

Abstract class and interface

When to create abstract class?
We create an abstract class when there is some common behaviour which can be reused across subclasses and certain behaviour needs to be defferred to the sublasses as they are subclass specific. We define such a behaviour using the abstract construct in java. Abstract classes help us achieve implementation inheritance.
When to create an interface?
When the client is only concerned with the behavior and does not worry about the actual implementation, then we should model such behavior using interface. Interface helps us achieve polymorphic interface inheritance.

So having said that,
  1. Abstract classes should be used when there is a strict heirarchy of classes i.e there is strict IS-A relationship between the classes. Ex FlatFileReader/XMLFileReader extends FileReader method loadFile is common behaviour and the procedure to load a flat file versus a XML file is the same however readFile can be sublass specific given the file types. With interface you can relate classes which are otherwise unrelated.
    Ex SoundBehaviour interface with method makeSound() can relate a Animal Class heirachy and Instrument class heirachy.
  2. Abstract classes should be used in cases where the base class needs to be changed often, the subclasses will inherit the behaviour without any change.Use of interfaces in such a case will make the design fragile, as changes to interfaces will be propogated to implementing classes.
Resources

No comments:

Post a Comment