Classes can add methods when they extend from a super class, but can they do the opposite and remove methods? The goal is for these removed classes to not be accessible at pile time. I'm essentially trying to get (new car()). to not autoplete .drive() in an IDE.
class vehicle {
drive() {
...
}
}
class car extends vehicle {
//previous attempt
private drive() { // can't modify public/private
}
}
Is there a way at pile time (tsc) to prevent car from having the method drive? Can we either delete it or modify it's accessibility?
Classes can add methods when they extend from a super class, but can they do the opposite and remove methods? The goal is for these removed classes to not be accessible at pile time. I'm essentially trying to get (new car()). to not autoplete .drive() in an IDE.
class vehicle {
drive() {
...
}
}
class car extends vehicle {
//previous attempt
private drive() { // can't modify public/private
}
}
Is there a way at pile time (tsc) to prevent car from having the method drive? Can we either delete it or modify it's accessibility?
Share Improve this question edited Oct 4, 2016 at 0:16 David asked Oct 4, 2016 at 0:14 DavidDavid 2,4471 gold badge15 silver badges23 bronze badges 4- 3 that violates the SSP tenat. – Daniel A. White Commented Oct 4, 2016 at 0:15
- 4 Inherited methods cannot be deleted or hidden. That would violate polymorphism. Could you explain what it is you're trying to acplish that makes you think it is necessary? – castletheperson Commented Oct 4, 2016 at 0:18
- 5 This is a red-flag that your class hierarchy is broken. – juanpa.arrivillaga Commented Oct 4, 2016 at 0:23
- What kinds of cars can't drive? – user663031 Commented Oct 4, 2016 at 3:25
3 Answers
Reset to default 3No. As noted in ments, this is indicative that your hierarchy is not correct. A derived class must always be substitutable for its base class.
You have to consider what happens when someone writes code like this
function doSomething(y: Vehicle) {
y.drive();
}
let x = new Car();
doSomething(x);
One way to sinalize to people in the IDE would be to add a @deprecated
ment in an overridden method's doc:
class MyClass {
/**
* @deprecated Please, don't use this because ...
*/
override iDontWantPeopleUsingThis() {
// Do nothing
}
}
That would render the method with a strikethrough format in the IDE.
I know it wasn't meant for this, but perhaps you can't fix your hierarchy.
You can consider overriding the method which will always throw error. This way you can restrict that function at runtime but not pile time.