我对使用 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 } }更多推荐
超类通用方法实现
发布评论