How to hide parent's method from the particular children in TypeScript?

Viewed 601

I’d like to hide some parent’s methods from particular ancestors. However, I can’t figure out how to do that.

Let’s say we’ve got:

class GrandPa {
   // must not be accessible from the GrandSon:
   protected gradPaDoing() {}
}

class Parent extends GrandPa {
   // Here probably must be some kind of adapter between GrandPa and GrandSon...
}

class GrandSon extends Parent {
   grandSonDoing() {
      this.gradPaDoing(); // I'd like to make it impossible
   }
}

Is there a way to achieve it?

1 Answers

I think your design has a flaw. Consider changing your design, if possible.

What I mean is: visibility is not supposed to be reduced down the hierarchy. It may be, however, increased if there need be. Just think about it, and it will make sense.

What you can do instead is, remove that grandPaDoing method all together from the ancestor class. Move it to an interface. And make your leaf classes implement that interface only if they need that behavior.

This approach will be cleaner, more consistent and more OOP way.

EDIT:

This solution still works for the case you mentioned in your comment. Here is how:

Let's say you want to rename anOldMethod to aNewMethod and prevent old method to be used anymore.

Then simply:

step1) create an interface, add aNewMethod into this interface and then make your leaf classes implement this interface.

step2) delete anOldMethod form parent class. If method is not there, it can not be accessed anymore. If you want, you can deprecate them by @Deprecated, as @toskv suggested.

Related