[英]Java: Inheriting constructor to the subclass
如我所知,构造函数,实例初始化块不会继承到子类,但是下面的代码继承了超类构造函数,为什么要调用它?
预期输出为 :来自缺点2
但其显示的输出如下 :--IIB--来自缺点1来自缺点2
WHY? this output , *As i know "sub class should not inherit Constructor & IIB block"*
请帮助我阐明这个概念。
public class X
{
{
System.out.println("--IIB--");
}
X()
{
System.out.println("from cons 1");
}
}
class Y extends X
{
Y()
{
System.out.print("from cons 2");
}
}
class Z
{
public static void main(String args[])
{
Y ob=new Y();
}
}
发生这种情况是因为:
Y()
{
System.out.print("from cons 2");
}
实际上变成
Y()
{
super(); //Call to X's constructor made here even if you don't call it
System.out.print("from cons 2");
}
这是因为每个Y
也是X
的实例。 必须在执行任何子构造函数之前先调用该父构造函数,以确保可以使用父属性。
编辑 :以下示例显示“子类未继承超类构造函数”:
class A {
A(int intForA) {
//Do stuff...
}
}
class B extends A {
B() {
this(3); //Won't compile! A's constructor isn't inherited by B
}
}
相反,我们这样做:
class B extends A {
B() {
super(3); //This compiles; we're calling A's constructor from B
}
}
“ Java编译器将初始化程序块复制到每个构造函数中。” -http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html
“如果构造函数没有显式调用超类构造函数,则Java编译器会自动将调用插入到超类的无参数构造函数中。” -http://docs.oracle.com/javase/tutorial/java/IandI/super.html
当您调用子类构造函数时,它会在内部使用super()
调用超类构造函数super()
最后链接页面的“注意”部分),在您的情况下, Y
的超类为X
同样,实例块被复制到构造函数中,并在调用该类的任何构造函数时执行。
来自init块文档
实例变量的初始化程序块看起来像静态初始化程序块,但没有static关键字:
{
// whatever code is needed for initialization goes here
}
Java编译器将初始化程序块复制到每个构造函数中。
因此按以下顺序输出。
--IIB--
---从实例块放入X
的构造函数中。
from cons 1
当在Y()
内部调用super()
时
from cons 2
- Y()
的SOP
在您的代码中Y extends X
因此理想情况下,当您创建Y
类对象时,它也会创建X
类对象。 因此,其块首先执行,然后执行X
构造函数,然后执行Y
构造函数。
因此,您将获得类似的输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.