Günter Zöchbauer
Günter Zöchbauer

Reputation: 657376

access field even when it is overridden

abstract class Base {

  Base() {
    loadDefaults();
  }

  Base.uninitialized();

  void loadDefaults() {}

  Map _values = {};

  operator [](String key) => _values[key];
}

class A extends Base {
  A() : super();

  A.uninitialized() : super.uninitialized();

  @override
  void loadDefaults() {
    _values.addAll(_defaults); // <=== loads g, h, i j instead of a, b, c, d ====|
    super.loadDefaults();
  }

  Map _defaults = {'a':'aVal', 'b': 'bVal', 'c': 'cVal', 'd': 'dVal'};
}

class B extends A {
  B() : super();

  B.uninitialized() : super.uninitialized();

  @override
  void loadDefaults() {
    _values.addAll(_defaults);
    super.loadDefaults();
  }

  Map _defaults = {'g': 'gVal', 'h': 'hVal', 'i': 'iVal', 'j': 'jVal'};
}

void main(args) {
  B settings = new B();

  print(settings['b']); // should print 'bVal'
  print(settings['g']); // prints 'gVal'
}

When I move each class in its own library the field _defaults of the subclass is not visible anymore and it works as desired. (I have to add the operator [] and the field _v to each class too to make this work, but that is fine in this use case)

Is there a way to access a field in the current class when it is overridden and the subclass is in the same library?

Upvotes: 0

Views: 35

Answers (1)

Vink
Vink

Reputation: 1277

This is a possibility to retrieve an attribute content as you can invoke an overridden method. But it's only accessible from the 'super' instance, because in the 'this' all has been replaced.

So in your case i have replaced the new _default attr, by the parent _default attr.

I don't know if it's enough for you but it's works as desired.

class B extends A {
  B() : super();

  B.uninitialized() : super.uninitialized();

  @override
  void loadDefaults() {
    _values.addAll(this._defaults);
    this._defaults = super._defaults;
    super.loadDefaults();
  }

  Map _defaults = {'g': 'gVal', 'h': 'hVal', 'i': 'iVal', 'j': 'jVal'};
}

Upvotes: 2

Related Questions