✅ Ensure that subclasses all have to override a specific method?
Is it possible to define a method in a class to say that it must be defined in every subclass?
For example, if I have:
I don't want C to be valid. I can't make
DoSomething()
in A
abstract, as I want to be able to instantiate A.
If this isn't possible in the language, then my approach will be to change A
to an abstract base class Base
with an abstract DoSomething()
, and a DoSomethingInternal()
, and then inherit A
from Base
and implement DoSomething()
there2 Replies
you can deliberately throw NotImplementedException as the default impl
Not quite sure what you're going to use it for tho due to lack of context, for example, for UIs it is reasonable to override the default style implementation BUT there's always the default implementation if you don't want to override them.
having to force a user to override some methods as a MUST to do requirement kinda eh
Thanks - that's useful - I could certainly do that, but it would only be caught at runtime, not at compile time
The only person I'm trying to protect here is myself - I had accidentally missed a couple of overrides
What I've now done is made sure that all of the non-abstract classes are sealed, and where I was subclassing a class that could also be instanced, I've made a shared abstract base class with a sealed subclass.
That way I can be confident that if all classes in this tree are either sealed or abstract, all classes that I might want to instance will have the abstract method defined