0
class A {
  A(int a);
}

class B extends A {
  final int b;

  B(int passed)
      : b = passed * 10,
        super(b); // Error
}

How can I pass b value to the superclass constructor?

iDecode
  • 22,623
  • 19
  • 99
  • 186

2 Answers2

1

You cannot pass the field to the superclass constructor because the field doesn't exist until all constructor initializers have completed (because the object doesn't exist yet).

If you want to introduce a name for an intermediate value, so you can refer to it twice, you can use an intermediate constructor:

class B {
  final int b;
  B(int passed) : this._(passed * 10);
  B._(this.b) : super(b);
}

This makes the B constructor a forwarding generative constructor, which allows it to evaluate expressions and pass the results to another generative constructor. That's the only way to give a name to an intermediate value during constructor initialization.

lrn
  • 64,680
  • 7
  • 105
  • 121
0

Initialization lists do not have read access to instance variables.

In a simple example like the one you have listed, you can just use passed * 10 instead of b

For more involved computations though, you may want to move to a factory constructor

class A {
  final int a;
  A(this.a);
}

class B extends A {
  final int b;

  factory B(int passed){
    var calculated;
    
    // some complicated calculation
    calculated= passed * 10;
    
    return B._(passed, calculated);
  }
  
  B._(int passed, int calculated)
    : b = passed,
    super(calculated);
}

main() {
  var b = B(2);
  print (b.a);
}

You can optionally keep the class interface clean by making the default constructor private as I have here.

Stephen
  • 4,041
  • 22
  • 39
  • The question should have been phrased 'Why can't I pass instance field to superclass'. Let me edit it now. Second, the solution you provided using factory constructor is overwhelming, why can't we just pass the instance field to superclass. – iDecode Aug 07 '20 at 11:33
  • You cannot access members of an object before the object has completed instantiation. Since the object is still being instantiated when the initializer list is used to initalize `b`, it is not permitted to be read from at that time. – Stephen Aug 07 '20 at 19:01