超类构造方法在Java中如何调用

发布时间:2025-12-19 20:17:34 作者:小樊
来源:亿速云 阅读:87

在Java中,子类可以通过super关键字来调用超类的构造方法。super关键字用于引用直接父类对象的一个实例。当创建子类对象时,子类的构造方法会隐式或显式地调用超类的构造方法。如果子类没有显式地调用超类的构造方法,那么编译器会自动插入一个对超类无参构造方法的调用。

以下是几种调用超类构造方法的场景:

1. 显式调用超类构造方法

在子类的构造方法中,可以使用super关键字显式地调用超类的构造方法。例如:

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

class Child extends Parent {
    public Child(String message) {
        super(message); // 显式调用超类的构造方法
        System.out.println("Child constructor called");
    }
}

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

在这个例子中,Child类的构造方法显式地调用了Parent类的构造方法。

2. 隐式调用超类构造方法

如果子类的构造方法没有显式地调用超类的构造方法,编译器会自动插入一个对超类无参构造方法的调用。例如:

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

class Child extends Parent {
    public Child() {
        // 隐式调用超类的无参构造方法
        System.out.println("Child default constructor called");
    }
}

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

在这个例子中,Child类的构造方法没有显式地调用超类的构造方法,编译器自动插入了对Parent类无参构造方法的调用。

3. 调用超类的特定构造方法

如果超类有多个构造方法,子类可以根据需要调用其中的一个。例如:

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

    public Parent(int number) {
        System.out.println("Parent constructor called with number: " + number);
    }
}

class Child extends Parent {
    public Child(String message) {
        super(message); // 调用超类的String参数构造方法
        System.out.println("Child constructor called with message");
    }

    public Child(int number) {
        super(number); // 调用超类的int参数构造方法
        System.out.println("Child constructor called with number");
    }
}

public class Main {
    public static void main(String[] args) {
        Child childWithMessage = new Child("Hello");
        Child childWithNumber = new Child(42);
    }
}

在这个例子中,Child类有两个构造方法,分别调用了Parent类的不同构造方法。

通过这些方式,子类可以在构造过程中调用超类的构造方法,确保超类的初始化逻辑得到执行。

推荐阅读:
  1. Java8中怎么操作Stream 对集合
  2. JAVA的List接口的remove重载方法调用原理是什么

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

java

上一篇:Ansible与云服务如何结合使用

下一篇:Java超类静态方法如何继承

相关阅读

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

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