温馨提示×

温馨提示×

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

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

Java Super超类与子类的构造函数调用顺序是什么

发布时间:2025-11-24 11:39:49 来源:亿速云 阅读:95 作者:小樊 栏目:编程语言

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

  1. 首先,调用父类(超类)的构造函数。如果父类有多个构造函数,编译器会根据传递给子类构造函数的参数选择合适的父类构造函数。如果父类没有显式定义构造函数,编译器会自动为父类生成一个默认的无参构造函数。

  2. 然后,调用子类的构造函数。如果子类有多个构造函数,编译器会根据创建子类对象时传递的参数选择合适的子类构造函数。

这种调用顺序确保了在子类对象创建过程中,父类的属性和方法已经被正确初始化。如果子类构造函数中没有显式调用父类构造函数,编译器会自动插入一个对父类无参构造函数的调用。

以下是一个简单的示例:

class Parent {
    Parent() {
        System.out.println("Parent constructor called");
    }
}

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

public class Main {
    public static void main(String[] args) {
        Child child = new Child();
    }
}

输出结果:

Parent constructor called
Child constructor called

如果父类没有无参构造函数,子类必须显式调用父类的一个带参数的构造函数,例如:

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

class Child extends Parent {
    Child() {
        super("Hello from child"); // 显式调用父类的带参数构造函数
        System.out.println("Child constructor called");
    }
}

public class Main {
    public static void main(String[] args) {
        Child child = new Child();
    }
}

输出结果:

Parent constructor called with message: Hello from child
Child constructor called
向AI问一下细节

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

AI