温馨提示×

温馨提示×

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

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

Java超类构造函数调用顺序

发布时间:2025-12-19 20:51:30 来源:亿速云 阅读:98 作者:小樊 栏目:编程语言

在Java中,当创建一个子类的对象时,构造函数的调用顺序遵循以下规则:

  1. 首先调用父类的构造函数。
  2. 然后调用子类的构造函数。

这个顺序是由Java语言规范定义的,以确保对象在创建时正确地初始化。

如果父类没有显式地定义构造函数,Java编译器会自动为父类提供一个默认的无参构造函数。在这种情况下,子类的构造函数会隐式地调用父类的默认构造函数。

如果父类定义了带参数的构造函数,但没有提供默认构造函数,那么子类必须显式地调用父类的带参数构造函数,否则会导致编译错误。这可以通过使用super关键字来实现。

以下是一个简单的示例,说明了构造函数的调用顺序:

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);
    }
}

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);
    }
}

public class Main {
    public static void main(String[] args) {
        Child child1 = new Child();
        System.out.println("----------------");
        Child child2 = new Child("Hello");
    }
}

输出:

Parent class constructor called
Child class constructor called
----------------
Parent class constructor called with message: Hello
Child class constructor called with message: Hello

从输出中可以看出,首先调用了父类的构造函数,然后调用了子类的构造函数。

向AI问一下细节

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

AI