Java – Using parent constructor in a child class in Java

constructorjava

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.

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?

I tried

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

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

Best Answer

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
    }
    // ....
}