可以避免在Java中对super()的默认调用吗? [英] Possible to avoid default call to super() in Java?
问题描述
假设出于某种原因,我不想隐式调用super()
,这在默认情况下是完成的.
Assume for some reason that I don't want to implicitly call super()
which is done by default.
class Animal {
public Animal() {
System.out.println("Constructing an animal.");
}
}
class Dog extends Animal {
public Dog() {
System.out.println("Constructing a dog.");
}
public static void main(String[] a) {
new Dog();
}
}
有什么方法可以禁用"创建新Dog时调用的默认行为?还是在原理和概念上是错误的?
Is there any way to "disable" the default behavior that super()
is invoked when making a new Dog? Or would that be principally and conceptually wrong?
我的意思是,在某些情况下,您可能只希望子类的构造函数而不调用基类的构造,而仍然继承基类.
I mean there could be cases where you would want only the constructor of the subclass and not invoke the construction of the baseclass, and still inherit the baseclass.
推荐答案
如果我正确理解了您想覆盖Animal
构造函数的行为,或者只是不调用它.如果是这样,那么您在概念上是错误的:您始终需要调用一个超级构造函数,您唯一可以进行的调用就是提供一个非默认的构造函数,即一个带有参数并提供适当的参数以影响该构造函数的行为(例如,通过选择其他构造函数,传递某种策略/功能对象等).
If I understand you correctly you want to override the behavior of the Animal
constructor or just not call it. If so you're conceptually wrong: you always need to call a super constructor, the only thing you could to with the calls is provide a non-default constructor, i.e. one with arguments and provide appropriate arguments to influence the behavior of that constructor (e.g. by either selecting a different constructor, passing some sort of strategy/function object etc.)
另一种方法可能是提供默认构造函数正在调用的某些init()
方法,您可以对其进行覆盖,但是存在一些问题,例如:
Another way might be to provide some init()
method that the default constructor is calling and which you can override but there are a few problems with it, e.g.:
- 如果重写的方法尝试访问仅对子类可见的任何内容(例如,其他字段),您可能会遇到问题,因为尚未初始化.
- 该方法无法初始化任何final字段.
这篇关于可以避免在Java中对super()的默认调用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!