Why does this() and super() have to be the first statement in a constructor?
Tom Ball
tball at google.com
Fri Oct 7 12:07:16 PDT 2011
If you have an initialization problem that is difficult to resolve in a
constructor, a common solution is to have a public factory method and a
private constructor.
Tom
On Fri, Oct 7, 2011 at 9:58 AM, Paul Benedict <pbenedict at apache.org> wrote:
> It's a compiler error because the superclass is guaranteed to be
> initialized first before the subclass.
>
> On Fri, Oct 7, 2011 at 11:51 AM, Vimil Saju <vimilsaju at yahoo.com> wrote:
> > If you have subclass then java requires that this() or super has to be
> first statement in the constructor of the subclass.
> > Here is an example
> >
> > publicclassMyClass{
> > publicMyClass(intx){}
> > }
> >
> > publicclassMySubClassextendsMyClass{
> > publicMySubClass(inta,intb){
> > intc =a +b;
> > super(c); // COMPILE ERROR
> > }
> > }The above compilation error can be resolved by rewriting the code in the
> constructor as follows
> >
> > publicclassMySubClassextendsMyClass{
> > publicMySubClass(inta,intb){
> > super(a + b);
> > }
> > }Can't the Java compiler detect that in the previous code there was no
> access to the instance fields or methods and therefore allow the code to
> compile without any error.
> >
> >
>
>
More information about the coin-dev
mailing list