Comparison : interface methods vs virtual methods vs abstract methods

情到浓时终转凉″ 提交于 2019-12-20 08:34:01

问题


What are the advantages and disadvantages of each of these?

  • interface methods
  • virtual methods
  • abstract methods

When one should choose what? What are the points one should keep in mind when making this decision?


回答1:


Virtual and abstract are almost the same. A virtual method has an implementation in the base class that can optionally be overridden, while an abstract method hasn't and must be overridden in a child class. Otherwise they are the same. Choosing between them depends on the situation. If you got a base implementation, you use virtual. If you don't, and you need every descendant to implement it for itself, you choose abstract.

Interface methods are implementations of a method that is declared in an interface that the class implements. This is quite unrelated to the other two. I think a method can be both virtual and interface. The advantage of interfaces is that you declare one interface (duh) that can be implemented by two totally different classes. That way, you can run the same code on two different classes, as long as the methods you'd like to call are declared in an interface they share.



来源:https://stackoverflow.com/questions/4762930/comparison-interface-methods-vs-virtual-methods-vs-abstract-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!