Abstract versus virtual methods

In the preceding example, we declared the Speak method as abstract. This forced our Dog class to provide an implementation of the method because, otherwise, we would get a compile-time error. Now, what if we don't want to have that particular restriction in our code?

We can do this by replacing the abstract method with the virtual method. The following is the changed implementation of the preceding code:

public abstract class Animal
{
public virtual void Speak()
{
}
}

Note that when you compile the code, there are no errors. Also, just for the sake of experimenting, comment out the Speak method in the Dog class.

Now, compile the program. Note that, unlike the previous case, when we use abstract methods, no compile-time errors occur:

In the next section, we will look at sealed classes and how they are implemented in C# applications.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.216.254