Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Superclass Common Method Implementation

Tags:

java

oop

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....

like image 662
n00bish Avatar asked Dec 04 '25 10:12

n00bish


2 Answers

You will want an abstract base class that defines what is done, while the child classes define how it is done. Here's a hint as to how such a thing might look

public abstract class BaseClass{

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

}

This is loosely related to the Template Method pattern, which might be of interest to you.

like image 98
Sean Patrick Floyd Avatar answered Dec 06 '25 00:12

Sean Patrick Floyd


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 printReponse method in the superclass, and make it abstract. Then write your print method in the superclass that does the common thing and calls printResponse when needed. Finally, override only printResponse in the 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
    }
}
like image 28
Sergey Kalinichenko Avatar answered Dec 05 '25 23:12

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!