java - Superclass Common Method Implementation -
i'm new oo programming java. have question pertaining inheritance.
i have printing method i'd common among subclasses. code in print method usable subclasses except response object specific each individual subclass.
i'm thinking need override method in each subclass providing specific implementation. feels there slicker way keep common method in super class , while somehow supplying specific response object based on subclass accessing it.
any thoughts? sorry if seems elementary....
you absolutely right, there better way. if implementations share great deal of code, can use template method pattern reuse implementation possible.
define printreponse
method in superclass, , make abstract. write print
method in superclass common thing , calls printresponse
when needed. finally, override printresponse
in subclasses.
public abstract class baseprintable { protected abstract void printresponse(); public void print() { // print common part printresponse(); // print more common parts } } public class firstprintable extends baseprintable { protected void printresponse() { // first implementation } } public class secondprintable extends baseprintable { protected void printresponse() { // second implementation } }
Comments
Post a Comment