Question

Whenever I define a private method like this:

class ParentClass {

  sayHi() { _initiateGreeting(); }
  _initiateGreeting() { print("I'm a parent class"); }

}

It is not possible to redefine it in a subclass:

class ChildClass extends ParentClass {
  _initiateGreeting() { print("I'm a child class"); } // redefining the method
}

Now if I create an instance of a ChildClass and call sayHi() method, then it is the private method from a ParentClass which actually gets called:

var child = new ChildClass();
child.sayHi(); // outputs "I'm a parent class"

If, however, _initiateGreeting() is made public everywhere (that is, stripped off the _) then calling child.sayHi() results in the output I'm a child class.

Why? How do I redefine a private method so that it gets called in a subclass?

Was it helpful?

Solution

Private member can be seen as library member. Inside a library there are no difference between members with or without a prepending underscore.

So if you're in the same library you should be able to redefined the method in subclass.

OTHER TIPS

What you are essentially asking for are protected methods. Alas, Dart doesn't have any.

But there is a very simple workaround, that might not be elegant, but nonetheless effective.

Just define a class ProtectedMethod within the same library as your MyClass. ProtectedMember has one private member--the "protected" method. MyClass then has a field protectedMethod of type ProtectedMethod. A consumer of your MyClass will of course see protectedMethod, but can't access the actual method. A user who subclasses your MyMethod just has to create a new ProtectedMethod and override the method in the constructor.

This approach might even have advantages, as this enables you to do sanity checks or force to call super without relying on flimsy annotations.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top