S
Sathyaish
I have some questions about calling constructors in Java:
1) Do I *have* to call the base/super class constructor from the
child's constructor as the *first* line of code or can I call it
afterwards also from within the child class' constructor?
As in, do I have to do this?
class Child extends Parent
{
public Child(somearg)
{
/* call the parent's constructor first */
super(somearg);
/* other stuff here */
}
}
Or do I have the liberty to do this?
class Child extends Parent
{
public Child(somearg)
{
/* some stuff first happens here */
/* later */
super(somearg);
}
}
I recall reading somewhere that the call to super has to be first line
of code in a child's constructor.
2) Does Java implicitly call super even when we don't explicitly call
it from a child? It makes sense because that is how object invocation
is sequenced. However, how does it know the params to pass? Or does it
do it call the non-parameterized constructor of the super class?
Because how else will it know of what parameters to pass?
3) Supposing the answer to question 2 above is "Yes, Java does call
non-parameterized constructors implicitly first, in order to create
the parent before creating the child," even then, can I explicitly
call the parent's constructor as indicated in question (1) (b) above?
1) Do I *have* to call the base/super class constructor from the
child's constructor as the *first* line of code or can I call it
afterwards also from within the child class' constructor?
As in, do I have to do this?
class Child extends Parent
{
public Child(somearg)
{
/* call the parent's constructor first */
super(somearg);
/* other stuff here */
}
}
Or do I have the liberty to do this?
class Child extends Parent
{
public Child(somearg)
{
/* some stuff first happens here */
/* later */
super(somearg);
}
}
I recall reading somewhere that the call to super has to be first line
of code in a child's constructor.
2) Does Java implicitly call super even when we don't explicitly call
it from a child? It makes sense because that is how object invocation
is sequenced. However, how does it know the params to pass? Or does it
do it call the non-parameterized constructor of the super class?
Because how else will it know of what parameters to pass?
3) Supposing the answer to question 2 above is "Yes, Java does call
non-parameterized constructors implicitly first, in order to create
the parent before creating the child," even then, can I explicitly
call the parent's constructor as indicated in question (1) (b) above?