Java 构造函数能调用父类构造器吗

发布时间:2025-01-22 20:28:33 作者:小樊
来源:亿速云 阅读:94

是的,在Java中,构造函数可以调用父类的构造器。在子类的构造函数中,可以使用super关键字来调用父类的构造器。这样做的目的是确保父类也被正确地初始化,从而避免潜在的问题。

当子类构造函数被调用时,Java会自动调用父类的无参构造器(如果存在)。但是,如果你需要调用父类的其他构造器,你需要显式地使用super关键字并传递相应的参数。

以下是一个示例:

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

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

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

    Child(String message) {
        super(message); // 调用父类的带参构造器
        System.out.println("Child constructor with message called");
    }
}

public class Main {
    public static void main(String[] args) {
        Child child1 = new Child();
        Child child2 = new Child("Hello, World!");
    }
}

输出:

Parent constructor called
Child constructor called
Parent constructor with message called
Child constructor with message called
推荐阅读:
  1. java抽象函数的作用
  2. Java中父类怎么调用子类的方法

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

java

上一篇:构造函数与 Java 方法有何不同

下一篇:什么是 Java 构造函数的隐式调用

相关阅读

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

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