Re: "call to super must be first statement in constructor"

From: Roland (roland_at_phony.biz)
Date: 01/30/05


Date: Sun, 30 Jan 2005 16:01:30 +0100

On 30-1-2005 12:39, Paul Chapman wrote:

> Here is an example code fragment:
>
> abstract class Outer
> {
> protected abstract int getValue();
> protected final int value;
> Outer() {
> value = getValue(); }
> }
>
> class Subclass extends Outer
> {
> protected int getValue() {
> return valueProvider.getValue(); }
> private final SomeClass valueProvider;
> Subclass(SomeClass aValueProvider) {
> valueProvider = aValueProvider;
> super(); }
> }
>
> Attempting to compile something like this produces the error message in the
> subject line.
>
> Switching the two lines in the Subclass constructor obviously won't work.
>
> Using a separate initialize() method to initialize Outer means that
> Outer.value can't benefit from the security of being final.
>
> Is there a way out of this tangle?
>
> Cheers, Paul
>
>

If Outer.getValue() is only there to provide an initial value, I would
model it differently, e.g. by passing the value to the constructor of
Outer. If valueProvider is not needed in the Subclass except for
providing the initial value, I would remove it as field of Subclass.

abstract class Outer
{
     protected final int value;
     Outer(int theValue) {
         this.value = theValue;
     }
}

class Subclass extends Outer
{
     //private final SomeClass valueProvider;
     Subclass(SomeClass aValueProvider) {
         super(aValueProvider.getValue());
         //this.valueProvider = aValueProvider
     }
}

-- 
Regards,
Roland de Ruiter
   ___      ___
  /__/ w_/ /__/
/  \ /_/ /  \


Relevant Pages