Abstract Classes - Java
Archive - Originally posted on "The Horse's Mouth" - 2009-05-16 17:26:08 - Graham Ellis
Let's say we're writing an accounts system, for example ... we have a base class that's a "line entry" and we have subclasses for "employee", "regularevent","capitalcost" and "course" ... then we can write four subclasses, and we'll never instantise (create) just a lineentry. The getcost method will differ for the employee and regularevent classes, as they are time dependent, whereas the capitalcost and course class methods return the same value irrespective of the time. So there needs to be a getcost method in each subclass.
But I want an array of lineentrys ... and I need to be able to call getcost on each of them and have it run a different (polymorphic) method. Solution - I define lineentry as an abstract class - i.e. one who's definition isn't complete and so the constructor cannot be called directly - and define the getcost method as abstract.
As an extra, if getcost is to be a different piece of code in various groups of subclasses, I can introduce extra intermediate abstract classes to ensure that each peice of code only has to be written once - this is shown in the diagram.