在Java中的子类中使用父构造函数

在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.

我相信默认情况下是父类调用class的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
    }
    // ....
}