Parent可以调用Child Class方法吗? [英] Can a Parent call Child Class methods?

查看:128
本文介绍了Parent可以调用Child Class方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

参考此处

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?

推荐答案

Class A 应该定义它要调用的方法(可能是抽象的方法,A应该是一个抽象类,根据Paul Haahr的优秀指南); B 可以(事实上具体必须,如果方法是抽象的)覆盖这些方法。现在,当在B类实例中发生时,从 A 中的其他方法调用这些方法,转到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".

这篇关于Parent可以调用Child Class方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆