超类通用方法实现

编程入门 行业动态 更新时间:2024-10-27 03:41:26
本文介绍了超类通用方法实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我对使用 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 } }

更多推荐

超类通用方法实现

本文发布于:2023-11-17 11:37:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1609887.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!