What is method overriding in c#?
Method overriding in C# is a feature of object-oriented programming that allows a subclass to provide its own implementation of a method that is already defined in its superclass. This means that when the subclass calls the method, its own implementation will be executed instead of the superclass's implementation.
To override a method in C#, you need to use the `override` keyword in the subclass method definition. The overridden method in the superclass must be marked as `virtual` or `abstract`.
Here is an example of method overriding in C#:
class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("The animal makes a sound");
}
}
class Cat : Animal
{
public override void MakeSound()
{
Console.WriteLine("Meow");
}
}
In this example, we define a class called `Animal` with a virtual method called `MakeSound()`. The `virtual` keyword allows subclasses to override this method. We then define a subclass called `Cat` that overrides the `MakeSound()` method with its own implementation.
When we call the `MakeSound()` method on a `Cat` object, the subclass's implementation will be executed:
Animal myAnimal = new Animal();
Cat myCat = new Cat();
myAnimal.MakeSound(); // outputs "The animal makes a sound"
myCat.MakeSound(); // outputs "Meow"
In this example, calling `MakeSound()` on the `Animal` object will execute the `Animal` class's implementation, while calling `MakeSound()` on the `Cat` object will execute the `Cat` class's implementation, demonstrating method overriding.
No comments:
Post a Comment
If you have any query kindly let me know.