Implicitly call method on all inherited classes

What is the best java programming practice to call a method on all inherited classes. Consider this pseudo code:

class TopLevel extends (SecondLevel extends Base)  

If all these classes have the method ‘serializeToString’, then how can I call this method throughout the inheritance structure? Te reason for this requirement, is that each class has its own variables it needs to serialize.
Also, there is a further requirement:
Each the class ‘TopLevel’ and ‘SecondLevel’ are not asbstract, and will need to be the entry point for serializing their entire inheritance.
Eg,

SecondLevel.serializeToString()

will need to call the method on ‘Base’ along with itself

And:

TopLevel.serializeToString()

Would need to call the method on both ‘SecondLevel’ and ‘Base’.

Currently, I have the serializeToString method in base, which then calls a method ‘addSerialization’ on the entire inheritance (and each implementation must call through to super to propagate the call)
While this works, it seems messy in my code to have two methods working to acheive one (simple?) thing.
What would the best way to acheive this be?


Source: oop

Leave a Reply