我对使用Java的OO编程相当新。我有一个关于继承的问题。
我有一种打印方法,我希望在子类中很常见。 print方法中的代码可用于所有子类,但特定于每个子类的响应对象除外。
我认为我需要覆盖每个子类中提供特定实现的方法。然而,感觉就像在超类中保持公共方法并且以某种方式基于访问它的子类提供特定响应对象一样。
有什么想法?对不起,如果这看起来很简单......
答案 0 :(得分:3)
您将需要一个定义完成内容的抽象基类,而子类定义 的完成方式。这是一个关于这样的事情看起来如何的暗示
public abstract class BaseClass{
public final String print(){
return "response object: " + responseObject();
}
protected abstract Object responseObject();
}
这与您可能感兴趣的Template Method模式松散相关。
答案 1 :(得分:2)
你是对的,有更好的方法。如果您的实现共享大量代码,则可以使用template method pattern重用尽可能多的实现。
在超类中定义printReponse
方法,并使其成为抽象方法。然后在执行常见事务的超类中编写print
方法,并在需要时调用printResponse
。最后,仅覆盖子类中的printResponse
。
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 :(得分:0)
你可以做这样的事情
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
即。您不需要覆盖print
方法,只需覆盖getResponse