I’m fairly new to OO programming specifically with Java. I have a question pertaining to inheritance.
I have a printing method that I’d like to be common among subclasses. The code in the print method is usable for all subclasses except for a response object that is specific to each individual subclass.
I’m thinking that i need to probably just override the method in each subclass providing the specific implementation. However it feels like there would be a slicker way to keep the common method in the super class and while somehow supplying the specific response object based on the subclass accessing it.
Any thoughts? Sorry if this seems elementary….
You are absolutely right, there is a better way. If your implementations share a great deal of code, you can use template method pattern to reuse as much implementation as possible.
Define a
printReponsemethod in the superclass, and make it abstract. Then write yourprintmethod in the superclass that does the common thing and callsprintResponsewhen needed. Finally, override onlyprintResponsein the subclasses.