In C#, a virtual
method is a method that can be overridden in subclasses. It allows for polymorphism, as a subclass can have its own implementation of the method while still being called through the base class.
To use a virtual method in C#, you need to declare the method as virtual
in the base class:
main.cs127 chars8 lines
Then, in the derived class, you can override the method using the override
keyword:
main.cs115 chars8 lines
When you call MakeSound()
on a Dog
object, the overridden method in the Dog
class is called instead of the base class implementation:
main.cs70 chars3 lines
This allows for flexibility in object-oriented programming, as you can use a base class to define a common behavior across objects, while still allowing for specific implementation in subclasses.
gistlibby LogSnag