温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java Subclass如何调用父类构造函数

发布时间:2026-01-09 15:56:50 来源:亿速云 阅读:99 作者:小樊 栏目:编程语言

在Java中,子类可以通过super()关键字调用父类的构造函数。super()必须在子类的构造函数中的第一行调用。如果子类没有显式地调用父类的构造函数,编译器会自动插入一个默认的super()调用。

以下是一个简单的例子,展示了如何在子类中调用父类的构造函数:

// 父类
public class Parent {
    public Parent() {
        System.out.println("Parent class constructor called");
    }

    public Parent(String message) {
        System.out.println("Parent class constructor called with message: " + message);
    }
}

// 子类
public class Child extends Parent {
    public Child() {
        super(); // 调用父类的无参构造函数
        System.out.println("Child class constructor called");
    }

    public Child(String message) {
        super(message); // 调用父类的带参数构造函数
        System.out.println("Child class constructor called with message: " + message);
    }
}

在这个例子中,Child类继承了Parent类。Child类有两个构造函数,一个无参构造函数和一个带参数的构造函数。在这两个构造函数中,我们分别使用super()和super(message)来调用父类的相应构造函数。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手