java - 为什么扩展抽象类的类中的方法即使没有被调用也会运行?
问题描述
考虑以下:
public class OuterClass {
static class NestedClass extends AbstractList<List<Integer>> {
void add(/* parameters here */) {
// note this method is not declared public
// print here does NOT appear in output
// implementation details here
}
public int size() {
// print here appears in output
// implementation details here
}
public List<Integer> get(int index) {
// print here appears in output
// implementation details here
}
}
public static List<List<Integer>> method(/* parameters here */) {
NestedClass nc = new NestedClass();
nc.add(..);
}
}
然后在一个单独的方法中,我创建一个NestedClass
. 当我运行代码时,没有调用get
or size
,打印语句出现在输出中。如何/为什么会发生这种情况?我理解这一点get
并且size
是必要的,因为AbstractList
它是扩展的,但我从不调用size
or get
。
一般来说,如果B
extends A
,是否会调用一个B
固有地调用在 中实现的重写抽象方法的方法B
?
谢谢
解决方案
这就是抽象类/方法的重点:您的基类定义了一组抽象方法和一组非抽象方法B。
现在,最有可能的是,集合B之外的方法将调用来自A 的方法。
换句话说:您使用抽象类来固定某些行为(通过从B存储桶中编写方法),但是为了允许不同的整体行为,您允许用户以不同的方式实现A方法(通过创建不同的子类,以不同的方式实现抽象方法)。
推荐阅读
- javascript - 将 select 的值添加到 href
- graphql - 有没有办法将到达 Apollo Server 的 GraphQL 查询传递到另一个 Apollo Server?
- c++ - 如何检查 PIMPL 不会重新编译客户端类
- android - 使用 PackageInstaller API 提示 apk 安装在 android 10 中不起作用
- c# - 在 Word 文档上设置背景图像
- google-chrome-extension - 哪个选项卡事件在可见选项卡中触发?
- java - GroovyShell 和类路径
- java - AndroidRuntime:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法
- mysql - 根据另一列的值将值插入新表中的列
- javascript - 导航栏在滚动后不显示导航链接