我有一个关于 Java 继承的问题。
我有两个类 A
和 B
和类 B,inherits from A:
public class A {
public A() {
System.out.println("Hi!");
}
}
public class B extends A {
public B() {
System.out.println("Bye!");
}
public static void main(String[] args) {
B b = new B();
}
}
当我运行程序 B 时,输出是:
Hi!
Bye!
Question : why the constructor of
class A
is invoked, when I create and object ofclass B
?
我知道 B 继承了 A 的所有内容——所有实例或类变量以及所有方法,从这个意义上说,B 的对象具有 A 的所有特征以及 B 中定义的一些其他特征。但是,我不知道并没有想到,当我创建一个B类型的对象时,A的构造函数也被调用了。 所以,写这个:
B b = new B();
创建两个对象 - 一个 B 类型,一个 A 类型。
这越来越有趣了,
有人可以解释为什么会发生这种情况吗?
最佳答案
它不会创建两个对象,只创建一个:B.
从另一个类继承时,您必须在构造函数中调用 super()。如果你不这样做,编译器会为你插入那个调用,你可以清楚地看到。
调用父类(super class)构造函数是因为否则对象将处于未初始化状态,子类的开发人员可能不知道。
编译器插入 super 调用后,你的子类实际上是这样的:
public class B extends A {
public B() {
super();
System.out.println("Bye!");
}
}
关于java - Java 中的继承——创建子类的对象也会调用父类(super class)的构造函数。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/488727/