Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there way for a class to 'remove' methods that it has inherited?

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?

like image 246
CJ7 Avatar asked May 06 '10 07:05

CJ7


People also ask

How can we avoid a method from being inherited?

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.

Is it possible to remove a member that is inherited?

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.

What is used to prevent class from being inherited?

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.

Can a class inherit from an inherited class?

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.


1 Answers

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.

like image 128
Jon Skeet Avatar answered Oct 08 '22 11:10

Jon Skeet