问题描述
参考此处
A是预编译的Java类(我也有源文件)B 是我正在创作的 Java 类
B 扩展 A.
A is a precompiled Java class (I also have the source file)B is a Java class that I am authoring
B extends A.
如何实现逻辑,使 A 可以调用 B 拥有的方法.
以下是条件:
How can logic be implemented such that A can call the methods that B has.
The following are the conditions:
- 我不想碰 A(只是作为最后一个选项,如果没有存在其他解决方案).
- 我不想使用反射.
如前所述,如果需要,我可以修改 A.无论哪种方式,可能的解决方案是什么?
As stated, if needed I could modify A.What could be the possible solution either way?
推荐答案
A
类应该定义它要调用的方法(可能是抽象的,A 应该是一个抽象类,根据 PaulHaahr 的优秀指南);B
可以(实际上是具体的 MUST,如果方法是抽象的)覆盖这些方法.现在,从 A
中的其他方法调用这些方法,当在类 B 的实例中发生时,转到 B 的覆盖.
Class A
should define the methods it's going to call (probably as abstract ones, and A should be an abstract class, per Paul Haahr's excellent guide); B
can (in fact to be concrete MUST, if the method are abstract) override those methods. Now, calls to those methods from other methods in A
, when happening in an instance of class B, go to B's overrides.
整体设计模式被称为模板方法;要覆盖的方法通常称为挂钩方法",执行调用的方法称为组织方法".
The overall design pattern is known as Template Method; the methods to be overridden are often called "hook methods", and the method performing the calls, the "organizing method".
这篇关于父类可以调用子类方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!