Reputation: 529
say i have a parent class and a child class and call the constructor of the child class. Would I have to have both the child constructors arguments plus the parent constructors arguments and use super( ) to initialize the parent. And does this mean if i overloaded the parents constructor I would need to have constructors matching each of the child's constructors... So if I had two parent constructors
parent(int a);
parent(int a,int b);
and two child constructors
child(int c);
child(int c,int d);
I would have to have child(int a) actually be in the form of two constructors
child(int a, int c)
{
super(a)
c = this.c;
}
and
child ( int a, int b, int c)
{
super(a,b)
c = this.c;
}
and have child(int c, int d) actually have two constructors
child(int a, int c, int d)
{
super(a);
c = this.c;
d = this.d;
}
or could i pass
child(int a,int b, int c, int d)
{
super(a,b);
c = this.c;
d = this.d;
}
}
Upvotes: 0
Views: 631
Reputation: 7899
Its up to you that how many overloaded version of construtor you want to write but keep in mind that every construtor of child class calls its super() with no arg implicitly if in parent no arg construtor is not there it will give you compile time error .but if yor are making in call explicitly you can call any supar construtor .
Upvotes: 0
Reputation: 23903
The parent constructor is always invoked. If not explicit it will be implicit. Its up to you to define the parameters to invoke the parent constructor.
If parent doesn't present a default constructor (one that doesn't requires any parameter) you need to invoke it explicitly from you sub classes.
Nothing forbids you to have a general constructor as you commented in case of child(int a, int b, int c, int d)
and invoke the parent class's constructor lie super(a,b)
.
If you have some constructors on the parent class doesn't mean necessarily that you need to "propagate" them on the sub classes.
There is a good text regarding the constructor chaining here.
Upvotes: 2