有没有办法一类以“删除”,该公司已经继承的方法? [英] Is there way for a class to 'remove' methods that it has inherited?
问题描述
有没有办法一类以删除,它继承了方法呢?
例如。如果我不希望我的班有一个的ToString()
方法我可以做一些事情,使其不再可用?
没有 - 这将违反里氏的替换原则。你应该总是能够使用一个亚型的实例,就好像它是一个超类的一个实例。
不要忘了,来电者可能只知道你的键入为基类型或接口。考虑下面的代码:
对象foo =新TypeWithToStringRemoved();
foo.ToString();
这不得不编译,不是吗?现在,你会期望在执行时会发生什么?
现在的的ToString
,的GetHashCode
,等于
和的GetType
有没有办法避免让他们摆在首位 - 但通常,如果有你想从基本类型为删除的方法,即意味着你不应该从它继承摆在首位。我个人觉得传承的作用,面向对象的编程是有点夸大了:它是非常有用的它的真正的有用的,但一般来说,我更喜欢继承组成和接口作为抽象的形式,而不是基类<。 / p>
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?
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.
这篇关于有没有办法一类以“删除”,该公司已经继承的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!