在 Java 的子类中使用父构造函数 [英] Using parent constructor in a child class in Java

查看:25
本文介绍了在 Java 的子类中使用父构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类ChildClass",它扩展了ParentClass"类.与其完全替换父类的构造函数,我想先调用父类的构造函数,然后再做一些额外的工作.

I have a class "ChildClass" that extends the class "ParentClass". Rather than completely replace the constructor for the parent class, I want to call the parent class's constructor first, and then do some extra work.

我相信默认情况下会调用父类的 0 参数构造函数.这不是我想要的.我需要使用参数调用构造函数.这可能吗?

I believe that by default the parent class's 0 arguments constructor is called. This isn't what I want. I need the constructor to be called with an argument. Is this possible?

我试过了

this = (ChildClass) (new  ParentClass(someArgument));

但这不起作用,因为您无法修改this".

but that doesn't work because you can't modify "this".

推荐答案

您可以在子级的构造函数中使用super"引用父级的构造函数.

You can reference the parent's constructor with "super", from within a child's constructor.

public class Child extends Parent {
    public Child(int someArg) {
        super(someArg);
        // other stuff
    }
    // ....
}

这篇关于在 Java 的子类中使用父构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆