所以我明白 super()
调用父类的构造函数,并且我已经多次使用它。但是,我从未在子类的构造函数之外使用过它。是否可以从子类构造函数外部调用 super()
?由于super
仅在附加到派生类时才有意义,因此可以将其视为派生类的成员函数吗?我最初在尝试使用对象调用 super 时遇到了这个问题(只是实验)。
可以做这样的事情吗?
class Animal {
Animal() {
System.out.println("Animal's constructor was called.");
}
}
class Puppy extends Animal {
Puppy() {
System.out.println("Puppy's constructor was called.");
}
}
public class Test {
public static void main(String[] args) {
Puppy pupper = new Puppy();
pupper.super();
}
}
最佳答案
不,这是不可能的,在构造函数主体之外是不可能的。
Java Language Specification § 8.8.7.1说如下:
ExplicitConstructorInvocation: [TypeArguments] this ( [ArgumentList] ) ; [TypeArguments] super ( [ArgumentList] ) ; ExpressionName . [TypeArguments] super ( [ArgumentList] ) ; Primary . [TypeArguments] super ( [ArgumentList] ) ;
这里,在构造函数主体 ( § 8.8.7 ) 中,允许使用 super()
,但其他地方都不允许。
关于java - super() 只能从子类构造函数中调用吗? | java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69248858/