Learning something new everyday...
Friday, 9. January 2009, 02:38:09
Not to sound prudish or something... I learn new ways of doing things in Java, and find new libraries to use, and find innovative ways of using existing libraries, and innovate around algorithms and stuff every single day... Its just been a long time (I'd say about a couple of years or so) that I learned something new about the Java language itself. Its not even something sensational or mindblowing or anything... It just pleasantly surprised me today.
Enough preamble, I don't really need a justification for posting on my own blog, do I?
Consider an abstract base class
AbstractBaseClass. This base class has a concrete implementation of a method
concreteMethod. The concreteMethod is basically in the AbstractBaseClass because the implementation depends on data already available in the objects of AbstractBaseClass, and not really those that the ConcreteSubclasses need to worry about.
Moving on, there is a specific abstract subclass of the AbstractBaseClass,
AbstractSubClass. This is an aberration of sorts, because all other subclasses of AbstractBaseClass are concrete... AbstractSubClass is not really that big an aberration, as it does have a few ConcreteSubSubclasses of its own..
So, where's the problem?
None, yet.
The problem arises when you realize that the implementation of concreteMethod in AbstractBaseClass is not really appropriate for the
ConcreteSubSubclassAand
ConcreteSubSubClassB, which are both concrete sub classes of AbstractSubClass. Wait a minute..., you realize... The implementation of concreteMethod is not really appropriate for any current, or future subclass of AbstractSubClass...
Which means that you have a concreteMethod in your AbstractBaseClass, which is perfect for all other concrete subclasses, except for concrete subclasses of AbstractSubclass, which need different handling per class for concreteMethod, which means that overriding concreteMethod in AbstractSubclass is not the answer.
How do you ensure that all subclasses of AbstractSubClass actually provide an implementation for concreteMethod, while maintaining the AbstractBaseClass implementation for all the rest (except those that need to override it anyways, stupid edge case...)??
<drum roll>
Apparently, it is legal to override a concrete method and erase the implementation, making it abstract, in AbstractSubclass, to enforce subclasses of AbstractSubclass to implement concreteMethod, as if it were just another abstractMethod, similar to some of the other abstractMethods in AbstractBaseClass.
...
...
That was it.
Have I managed to confuse someone?
I'll try and maybe draw a figure or something tomorrow... Maybe some code samples might help...
Then again, maybe the idea won't seem so awesome, after I've paid off a bit of my sleep debt, so don't hold your breath much....




