为什么你需要知道抽象类的方法是否是抽象的
有人问我一个问题。其内容如下:
抽象类的API文档告诉你一个方法是否 是抽象的。您何时以及为什么需要知道这一点?
任何帮助将不胜感激。
I've been asked a question. It is the following:
The API documentation of an abstract class tells you whether a method
is abstract. When and why would you need to know this?
Any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要知道哪些方法是抽象的,因为您需要在继承类时提供这些方法的实现。
You need to know what methods are abstract because you will need to provide implementations for those methods when inheriting the class.
作为 Fredrik 答案的扩展,它还指定了要更改哪些行为。
您通常可以重写一个方法(如果该方法不是最终的并且该类也不是最终的),但在实践中,如果该类不是专门为更改而设计的,那么这可能会非常棘手。现有方法可能会假定您重写的方法的某种行为,但未指定(它会发生)并且您未提供。
通过显式声明一个方法是抽象的,您表达了该方法将由其他人实现的意图。这通常也意味着抽象方法的文档在预期行为方面更加完整。
As an extension to Fredrik's answer, it also specifies which behaviour is intended to be changed.
You can usually override a method (if the method is not final and the class is not final) but in practice that can be very tricky if the class is not specifically designed for changes. It may be that existing methods assume some kind of behaviour of the method you override, which is not specified (it happens) and that you do not provide.
By explicitly declaring a method to be abstract you express the intention that the method will be implemented by someone else. It also usually means that the documentation of an abstract method is a bit more complete with regards to expected behaviour.
如果您调用抽象方法,您需要考虑到实际实现在其他地方,并且可能在行为上有一些变化。
If you call the abstract method you need to take into account that the actual implementation is elsewhere and may have some variation in behavior.
您知道该方法是否是抽象的,因为在这种情况下您必须在具体(继承)类中实现它。
我建议你看看以下关于设计模式的书籍,因为他们提到了这些东西并且也有实践:
http: //oreilly.com/catalog/9780596007126
you have know if the method is abstract, because in that case you have to implement it in your concrete (inherited) class.
I advice you to take a look on the following books about Design Patterns, because they mention these stuff and have practices too:
http://oreilly.com/catalog/9780596007126