Java子类构造方法怎样调用父类构造器

发布时间:2025-03-06 10:45:57 作者:小樊
来源:亿速云 阅读:129

在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()关键字来调用父类相应的构造方法。当我们创建一个Child对象时,将按照以下顺序调用构造方法:

public static void main(String[] args) {
    Child child1 = new Child(); // 输出:Parent class constructor called
                                   // 输出:Child class constructor called

    Child child2 = new Child("Hello"); // 输出:Parent class constructor called with message: Hello
                                       // 输出:Child class constructor called with message: Hello
}

注意,如果子类构造方法没有显式地调用父类构造方法,编译器会自动插入一个无参数的super()调用。但是,如果父类没有无参数构造方法,那么子类必须显式地调用父类的带参数构造方法,否则会导致编译错误。

推荐阅读:
  1. C#RSA对接JAVA中RSA方式的示例分析
  2. Node调用Java的示例代码

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

java

上一篇:OpenHarmony图表未来发展趋势如何

下一篇:如何使用OpenHarmony图表提升效率

相关阅读

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

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