Standard superclass implementation

I am new to OO programming specifically for Java. I have a question related to inheritance.

I have a printing method that I would like to propagate among subclasses. The code in the print method can be used for all subclasses except for the response object, which is specific to each individual subclass.

I think I need to rather override the method in each subclass providing a concrete implementation. However, it looks like the superclass will use a simpler way to keep the generic method and somehow provide a specific response object based on the subclass's access to it.

Any thoughts? Sorry if this seems elementary ....

+3


source to share


3 answers


You are absolutely right, there is a better way. If you have a lot of code in your implementations, you can use the template pattern template to reuse as much of the implementation as possible.

Define a method printReponse

in the superclass and make it abstract. Then write your method print

in a superclass that does the usual thing and will call if needed printResponse

. Finally, override only printResponse

in subclasses.



public abstract class BasePrintable {
    protected abstract void printResponse();
    public void print() {
        // Print the 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
    }
}

      

+2


source


You will need an abstract base class that defines what is done and child classes define how it is done. Here's a hint of how such a thing might look

public abstract class BaseClass{

    public final String print(){
        return "response object: " + responseObject();
    }
    protected abstract Object responseObject();

}

      



This has little to do with the Template Method you might be interested in.

+3


source


You can do something like this

public class A {
     protected String getResponse(){ return "Response from A"; }
     public void print(){
          System.out.println( this.getName() );
     }
}

public class B extends A {
     protected String getResponse(){ return "Response from B"; }
}

A a = new A();
B b = new B();

a.print(); // Response from A
b.print(); // Response from B

      

i.e. you don't need to override the method print

, justgetResponse

0


source







All Articles