企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
### [带参数的构造函数](https://lingcoder.gitee.io/onjava8/#/book/08-Reuse?id=%e5%b8%a6%e5%8f%82%e6%95%b0%e7%9a%84%e6%9e%84%e9%80%a0%e5%87%bd%e6%95%b0) 上面的所有例子中构造函数都是无参数的 ; 编译器很容易调用这些构造函数,因为不需要参数。如果没有无参数的基类构造函数,或者必须调用具有参数的基类构造函数,则必须使用**super**关键字和适当的参数列表显式地编写对基类构造函数的调用: ~~~ // reuse/Chess.java // (c)2017 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Inheritance, constructors and arguments class Game { Game(int i) { System.out.println("Game constructor"); } } class BoardGame extends Game { BoardGame(int i) { super(i); System.out.println("BoardGame constructor"); } } public class Chess extends BoardGame { Chess() { super(11); System.out.println("Chess constructor"); } public static void main(String[] args) { Chess x = new Chess(); } } /* Output: Game constructor BoardGame constructor Chess constructor */ ~~~ 如果没有在**BoardGame**构造函数中调用基类构造函数,编译器就会报错找不到`Game()`的构造函数。此外,对基类构造函数的调用必须是派生类构造函数中的第一个操作。(如果你写错了,编译器会提醒你。)