![](/img/trans.png)
[英]How to call the superclass implementation of an overridden method from inside the superclass in Java?
[英]Superclass Common Method Implementation
我对使用Java的OO编程很新。 我有一个关于继承的问题。
我有一个打印方法,我希望在子类中很常见。 print方法中的代码可用于所有子类,但特定于每个子类的响应对象除外。
我想我可能只是覆盖每个子类中提供特定实现的方法。 然而,感觉就像在超类中保持公共方法并且以某种方式基于访问它的子类提供特定响应对象一样。
有什么想法吗? 对不起,如果这看起来很......
您将需要一个定义完成内容的抽象基类,而子类定义它是如何完成的。 这是一个关于这样的事情看起来如何的暗示
public abstract class BaseClass{
public final String print(){
return "response object: " + responseObject();
}
protected abstract Object responseObject();
}
这与模板方法模式松散相关,您可能会对此感兴趣。
你是绝对正确的,还有更好的方法。 如果您的实现共享大量代码,则可以使用模板方法模式尽可能多地重用实现。
在超类中定义printReponse
方法,并使其成为抽象方法。 然后在执行常见printResponse
的超类中编写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
}
}
你可以做这样的事情
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.