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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With