简体   繁体   中英

Comparison : interface methods vs virtual methods vs abstract methods

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM