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".
A constructor cannot be called as a method. It is called when object of the class is created so it does not make sense of creating child class object using parent class constructor notation.
If the child class constructor does not call super , the parent's constructor with no arguments will be implicitly called. If parent class implements a constructor with arguments and has no a constructor with no arguments, then the child constructors must explicitly call a parents constructor.
Define a constructor in the child class To call the constructor of the parent class from the constructor of the child class, you use the parent::__construct(arguments) syntax. The syntax for calling the parent constructor is the same as a regular method.
That depends on what you mean by "use." If you mean, does the default constructor for a child class call the parent constructor, then yes, it does (more below). If you mean, is a default constructor matching whatever parameters the parent constructor has created automatically, then no, not in the general case.
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 } // .... }
To invoke a specific parent-class constructor, put super(param1, param2, ...)
as the first statement in the child-class constructor body.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With