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

Popular posts from this blog

delphi - How to convert bitmaps to video? -

jasper reports - Fixed header in Excel using JasperReports -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -