Java构造函数继承? [英] Java constructor inheritance?

查看:65
本文介绍了Java构造函数继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直认为构造函数不是继承的,但请看下面的代码:

I always thought that constructors aren't inherited, but look at this code:

class Parent {
    Parent() {
        System.out.println("S1");
    }
}

class Child extends Parent {
    Child() {
        System.out.println("S2");
    }
}

public class Test5 {
    public static void main(String[] args) {
        Child child = new Child();
    }
}

//RESULT:
//S1
//S2

它表明Child继承了构造函数。为什么结果有S1?是否有可能创建2个没有参数的构造函数,并且在结果上仅具有Child构造函数,而没有基本构造函数(仅S2)?

It shows that Child inherited constructor. Why there is S1 on result? Is there any possibility to create 2 constructors without parameters and have only Child constructor on result without base constructor (only S2)?

推荐答案

无论您在这里看到什么,都称为构造函数链接。现在什么是构造函数链接:

Whatever you are seeing here is called as constructor chaining. Now What is Constructor Chaining:


构造函数链接通过使用继承发生。子类
构造函数方法的第一个任务是调用其超类的构造函数
方法。这样可以确保子类对象的创建从
开始,并在继承
链中对其上方的类进行初始化。

Constructor chaining occurs through the use of inheritance. A subclass constructor method's first task is to call its superclass' constructor method. This ensures that the creation of the subclass object starts with the initialization of the classes above it in the inheritance chain.

继承链中的类数。每个
构造函数方法都将调用该链,直到到达并初始化顶部
的类为止。然后,下面的每个后续类都将
初始化,因为链条回落到原始子类。
此过程称为构造函数链接。(

There could be any number of classes in an inheritance chain. Every constructor method will call up the chain until the class at the top has been reached and initialized. Then each subsequent class below is initialized as the chain winds back down to the original subclass. This process is called constructor chaining.(Source)

这就是程序中发生的事情。编译程序时, Child javac 编译为这种方式:

That's what happening in your program. When you compile your program , your Child is compiled to this way by javac:

class Child extends Parent 
{ 
  Child()
  {
    super();//automatically inserted here in .class file of Child
    System.out.println("S2");
  }
}

并且您的Parent类转换为以下内容:

And your Parent class is converted to following:

Parent() 
{
    super();//Constructor of Object class
    System.out.println("S1");
}

这就是为什么您的输出显示为:

That's why your output is showing as:

S1 //output from constructor of super class Parent
S2 //output from constructor of child Class Child

这篇关于Java构造函数继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆