我从一个名为 ChildClass
的抽象类扩展,它有 4 个应该实现的构造函数。
有一组所有构造函数通用的通用配置。
我可以抽象这些任务并在所有构造函数中调用它。
当要初始化对象时是否有调用特定方法而不是在所有构造函数签名中调用它?
最佳答案
由于Java编译器必须确保调用基类的构造函数,因此您可以将公共(public)代码放在抽象基类的构造函数中:
abstract class BaseClass {
protected BaseClass(/*put arguments here*/) {
// Code that is common to all child classes
}
}
class ChildClassOne extends BaseClass {
public ChildClassOne(/*put arguments here*/) {
super(arg1, arg2, ...);
// More code here
}
}
关于java - 当对象初始化时调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39469318/