超类通用方法实现 [英] Superclass Common Method Implementation

查看:68
本文介绍了超类通用方法实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用 Java 进行 OO 编程还很陌生.我有一个关于继承的问题.

I'm fairly new to OO programming specifically with Java. I have a question pertaining to inheritance.

我有一个打印方法,希望在子类中通用.print 方法中的代码可用于所有子类,但特定于每个子类的响应对象除外.

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.

在超类中定义一个printReponse方法,并使其抽象.然后在超类中编写您的 print 方法,该方法执行常见操作并在需要时调用 printResponse.最后,仅覆盖子类中的 printResponse.

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

这篇关于超类通用方法实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆