Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using parent constructor in a child class in Java

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

like image 386
some guy Avatar asked Nov 08 '11 18:11

some guy


People also ask

Can a child class use parent class constructor?

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.

Does child class call parent constructor in Java?

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.

How do you call a constructor of parent class in child class?

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.

Does a child class always call the parent constructor?

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.


Video Answer


2 Answers

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     }     // .... } 
like image 182
misberner Avatar answered Sep 30 '22 17:09

misberner


To invoke a specific parent-class constructor, put super(param1, param2, ...) as the first statement in the child-class constructor body.

like image 43
maurizeio Avatar answered Sep 30 '22 15:09

maurizeio