mrd2242
mrd2242

Reputation: 95

Dart: instance variable override

I'm confusing about the rules of class instance variable override

class S0 {
  num a;

  S0(this.a) {
    print("in S0 :$a");
  }
}

class S1 extends S0 {
  num a;

  S1(this.a) : super(a + 1) {
    print("in S1 :$a");
  }
}

main() {
  var b = S1(123);
  print(b.a);
}

Above is my code. I expect it prints:

in S0 :124

in S1 :123

123

But the result is:

in S0 :123

in S1 :123

123

Why? thanks!

Upvotes: 0

Views: 577

Answers (2)

linxie
linxie

Reputation: 2167

because in the constructor body access to this (and its members) is allowed. so getter and setter is generated before execute constructor.

according to instance variable

All instance variables generate an implicit getter method. Non-final instance variables also generate an implicit setter method.

and as described in Dart Programming Language Specification Chapter 10.8.1 Inheritance and Overriding

Instance variables never override each other. The getters and setters induced by instance variables do.

so when you call this.a in class S0 it's already overrided by child class S1;

Upvotes: 1

jamesdlin
jamesdlin

Reputation: 90184

In Dart, instance variables implicitly create getter and (for non-final members) setter functions. That is, S0's interface is implicitly:

class S0 {
  num get a;
  set a(num value);

  S0(num a);
}

From this perspective, it should be clearer that when S0 attempts to access a, it uses its getter method, which in this case is overridden by S1 and thus always returns S1's value.

The construction order is also important. Constructing an instance of the derived S1 class would execute:

  1. The initialization list from the derived class (S1).
  2. The initialization list from the base class (S0).
  3. The constructor body from the base class (S0).
  4. The constructor body from the derived class (S1).

After step 2, the object is considered sufficiently constructed for virtual dispatch to work (i.e., for overrides in the derived class to be called). (This is unlike languages such as C++ where objects are constructed purely from base class to derived and virtual dispatch in constructors is disallowed to prevent invoking methods on unconstructed objects.)

Upvotes: 2

Related Questions