Is there way for a class to 'remove' methods that it has inherited?
E.g. if I don't want my class to have a ToString()
method can I do something so that it is no longer available?
You can prevent a class from being subclassed by using the final keyword in the class's declaration. Similarly, you can prevent a method from being overridden by subclasses by declaring it as a final method. An abstract class can only be subclassed; it cannot be instantiated.
No inherited members can be removed, ever. This is not how inheritance works. You can override a virtual method or virtual getter or setter of a property. Also, quite simply, you can hide an inherited member by a new member of the same type, but the inherited member will always be there and accessible.
To prevent inheritance, use the keyword "final" when creating the class. The designers of the String class realized that it was not a candidate for inheritance and have prevented it from being extended.
Inheritance allows us to define a class that inherits all the methods and properties from another class. Parent class is the class being inherited from, also called base class. Child class is the class that inherits from another class, also called derived class.
No - this would violate Liskov's Substitution Principle. You should always be able to use an instance of a subtype as if it were an instance of a supertype.
Don't forget that a caller may only be aware of your type "as" the base type or an interface. Consider this code:
object foo = new TypeWithToStringRemoved(); foo.ToString();
That would have to compile, wouldn't it? Now what would you expect to happen at execution time?
Now for ToString
, GetHashCode
, Equals
and GetType
there's no way to avoid having them in the first place - but usually if there are methods you want to "remove" from a base type, that suggests you shouldn't be inheriting from it in the first place. Personally I find the role of inheritance is somewhat overplayed in object oriented programming: where it's useful it's really useful, but generally I prefer composition over inheritance, and interfaces as a form of abstraction rather than base classes.
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