gpt4 book ai didi

java - 在 java 中使用默认构造函数,即使存在参数化构造函数

转载 作者:行者123 更新时间:2023-12-01 06:26:50 25 4
gpt4 key购买 nike

我只是想在这里澄清我的概念,所以我问......

如果我为我的类定义了显式参数化构造函数,我仍然可以调用 java 编译器提供的默认构造函数(默认为每个类提供)吗??

或者在这种情况下会导致编译时错误吗?请解释编译器进行的调用究竟发生了什么!

最佳答案

当且仅当未提供构造函数,编译器才会创建无参构造函数。

JLS 在 Chapter 8 中指出:

If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.

一个“陷阱”是:

It is a compile-time error if a default constructor is implicitly declared but the superclass does not have an accessible constructor (§6.6) that takes no arguments and has no throws clause.

关于java - 在 java 中使用默认构造函数,即使存在参数化构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10827346/

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