How do I force a polymorphic call to the super method?(如何强制对超级方法进行多态调用?)
问题描述
我有一个在广泛的层次结构中使用和覆盖的 init 方法.然而,每个 init 调用都扩展了前一个所做的工作.所以很自然,我会:
I have an init method that is used and overridden through out an extensive heirarchy. Each init call however extends on the work that the previous did. So naturally, I would:
@Override public void init() {
super.init();
}
这自然会确保所有内容都被调用和实例化.我想知道的是:我可以创建一种方法来确保调用超级方法吗?如果没有调用所有的 init,则对象中存在故障,因此如果有人忘记调用 super,我想抛出异常或错误.
And naturally this would ensure that everything is called and instantiated. What I'm wondering is: Can I create a way to ensure that the super method was called? If all of the init's are not call, there is a break down in the obejct, so I want to throw an exception or an error if somebody forgets to call super.
TYFT~艾顿
推荐答案
如果派生类未能调用超类,以下是引发异常的一种方法:
Here's one way to raise an exception if a derived class fails to call up to the superclass:
public class Base {
private boolean called;
public Base() { // doesn't have to be the c'tor; works elsewhere as well
called = false;
init();
if (!called) {
// throw an exception
}
}
protected void init() {
called = true;
// other stuff
}
}
这篇关于如何强制对超级方法进行多态调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何强制对超级方法进行多态调用?
基础教程推荐
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
