java - 调用当前类或父类(super class)的重载构造函数

标签 java constructor

在java中,类中的构造函数可以调用其父类(super class)的重载构造函数(比如说我们是否想显式且有意地进行该调用)。我知道类中的构造函数隐式调用父类(super class)的无参数默认构造函数(使用 super (); )。但是假设我调用一个重载的父类(super class)构造函数(例如 super(String s); ),那么我的问题是,这可能吗?如果这是可能的,那么对 super() 的调用是否仍然在 super(String s) 之前进行,其含义是什么?同一类的两个构造函数(一个无参数和一个重载)是否可以互相调用?如果这样做,他们会不会陷入循环?

最佳答案

你可以在其官方教程中得到答案: https://docs.oracle.com/javase/tutorial/java/IandI/super.html

具体阅读此内容:

The syntax for calling a superclass constructor is

    super();   

or:

    super(parameter list); 

With super(), the superclass no-argument constructor is called. With super(parameter list), the superclass constructor with a matching parameter list is called.

Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem. If a subclass constructor invokes a constructor of its superclass, either explicitly or implicitly, you might think that there will be a whole chain of constructors called, all the way back to the constructor of Object. In fact, this is the case. It is called constructor chaining, and you need to be aware of it when there is a long line of class descent.

所以回答你的问题: 是的,这是可能的,也是可行的。当您使用参数显式调用 super 构造函数时,只会调用该构造函数。

并且,请确保 super 构造函数调用是构造函数中的第一行,否则将显示编译器错误。

*****已编辑*****

并且,您只能隐式或显式调用一个特定的父类(super class)构造函数。当调用该父类(super class)构造函数时,不会调用其他父类(super class)构造函数,除非在您调用的父类(super class)构造函数中调用它。同时,如果在同一个类中多个构造函数相互递归调用,则无法编译 - 它将被编译器拒绝。

希望这有帮助。

关于java - 调用当前类或父类(super class)的重载构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35098881/

相关文章:

php - PHP 构造函数的用途

java - 匹配域中除查询之外的所有 url

java - Apache POI 清除卡住/拆分 Pane

适用于 Pig 的 Java UDF 日期正则表达式提取器?

java - 没有找到适合 getText(String) 的方法

c++ - 为什么我们将按引用传递的值视为地址?

java - 将多个索引项转换为流的最简单方法

c++ - 带空括号的默认构造函数

java - 如何实现扩展类的构造函数

javascript - 如何创建具有未分配属性的 Javascript 构造函数/原型(prototype)?