Comparison : interface methods vs virtual methods vs abstract methods

Nawaz picture Nawaz · Jan 21, 2011 · Viewed 26.3k times · Source

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?

Answer

GolezTrol picture GolezTrol · Jan 21, 2011

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.