Home > Software design >  Dart: Inherit some of the public methods privately
Dart: Inherit some of the public methods privately

Time:09-20

I want to inherit a class, but I want to make some of its methods private, which allows mutation of the object. I do not want to override those methods, as that will make them still accessible and cause a runtime error. I want something like this:-

class BaseClass {
  //...
  void update() {/*Implementation*/}
  void read() {/*Implementation*/}
}

class ChildClass extends BaseClass {
  //...
  void read() {/*Implementation*/}
}

int main() {
  final first = BaseClass(), second = ChildClass();
  first.update(); //Works
  second.update(); //Error: Method does not exist.
}

CodePudding user response:

I don't think what you want it possible. The entire point of extending classes is that child classes can access all public methods of the superclass. You might want to use composition instead. That would be something like:

class BaseClass {
  //...
  void update() {/*Implementation*/}
  void read() {/*Implementation*/}
}

class ChildClass {
  BaseClass _baseClass
  //...
  void read() { _baseClass.read() }
}
  • Related