开发者

Abstract and virtual same meaning?

开发者 https://www.devze.com 2023-02-03 07:24 出处:网络
As per different syntax and where it can b开发者_JS百科e used, they both seem very closely related. What are the major differences? abstract means that a derived class is forced to implement it while

As per different syntax and where it can b开发者_JS百科e used, they both seem very closely related. What are the major differences?


abstract means that a derived class is forced to implement it while with virtual this is not the case (it can but it is not required). This stems from the fact that an abstract method has no associated body while a virtual method does.


By defining a member as abstract, you are defining a kind of placeholder, without providing any default implementation. Any client code that interacts with the base class can still refer to the abstract placeholder member, safe in the knowledge that the concrete class of the instance must have provided a concrete implementation.

By defining a member as virtual, you enable derived classes to provide an implementation that will override that of the base class. The difference is that, if the derived class doesn't provide its own implementation, the one from the base class will be used.

Consider the following C# example classes:

abstract class TaskBase {
    public abstract void RunTask();
}

class RoadNetwork {
    public string GetCorrectSideToDriveOn() { return "left"; }
}

The design of the TaskBase class forces a derived class to provide its own implementation of RunTask() because the code won't compile without it. The designer is effectively saying "Tasks must be runnable, but you must provide the implementation because there isn't a meaningful default."

The design of the RoadNetwork class works differently: anyone who implements a RoadNetwork will automatically use the correct side of the road to drive on, unless they specifically choose to drive on the wrong side ;)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号