gpt4 book ai didi

java - 为什么异常应该在继承中处理,因为构造函数不是继承的?

转载 作者:行者123 更新时间:2023-12-04 21:28:27 78 4
gpt4 key购买 nike

据我所知,构造函数不是继承的。

那么在子构造函数中处理异常的原因是什么。在我们创建子对象或其他对象时,是否有人在幕后创建父对象?

public class Parent {
public Parent() throws Exception{

}
}

class Child extends Parent {
public Child(){ // compile time error "Unhandled Exception Type"

}
}

我并没有尝试通过在子构造函数中调用 Super() 来初始化父类。我不明白为什么我们必须这样做。

提前致谢。

最佳答案

引用JLS 8.8.7 Constructor Body

If a constructor body does not begin with an explicit constructor invocation ... then the constructor body implicitly begins with a superclass constructor invocation super();

换句话说,以下代码在语义上与您的 Child 类的定义相同:

class Child extends Parent {
public Child(){ // compile time error "Unhandled Exception Type"
super(); // This throws Exception.
}
}

这必须发生,因为初始化 Parent 实例所必需的初始化必须发生。考虑如果不调用 super 构造函数会发生什么:

class Parent {
private final Frobnitz foo;

Parent() throws Exception {
foo = new Frobnitz();
}

void doSomething() {
foo.doYourFrobbing();
}
}

class Child extends Parent { ... }

class Main {
public static void main(String[] args) {
new Child().doSomething(); // Would cause a NPE unless Parent() is called (implicitly or explicitly).
}
}

关于java - 为什么异常应该在继承中处理,因为构造函数不是继承的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32335282/

78 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com