Method overriding in C# Example
Method overriding in C# allows a derived class to provide a specific implementation of a method that is already defined in its base class. To override a method in C#, you use the `override` keyword. Here's an example demonstrating method overriding in C#:
Let's consider a base class `Shape` with a method `CalculateArea()`:
```csharp
using System;
class Shape
{
public virtual void CalculateArea()
{
Console.WriteLine("Calculating area in the base class (Shape).");
}
}
```
In the above code, the `CalculateArea()` method is marked as `virtual`, indicating that it can be overridden by derived classes.
Now, let's create a derived class `Circle` that overrides the `CalculateArea()` method:
```csharp
class Circle : Shape
{
private double radius;
public Circle(double radius)
{
this.radius = radius;
}
// Method overriding
public override void CalculateArea()
{
double area = Math.PI * radius * radius;
Console.WriteLine($"Calculating area of the circle: {area}");
}
}
```
In the `Circle` class, we use the `override` keyword to indicate that we are providing a specific implementation of the `CalculateArea()` method defined in the base class `Shape`. We calculate the area of the circle in the overridden method.
Now, you can create objects of the `Circle` class and call the `CalculateArea()` method. The overridden method in the `Circle` class will be executed:
```csharp
class Program
{
static void Main(string[] args)
{
Shape shape = new Circle(5.0); // Creating a Circle object as a Shape
shape.CalculateArea(); // Calls the overridden method in Circle class
Console.ReadKey();
}
}
```
In this example, even though the `shape` variable is of type `Shape`, it points to an instance of `Circle`. When `CalculateArea()` is called, it executes the overridden method in the `Circle` class, demonstrating method overriding in C#.
No comments:
Post a Comment
Comments Welcome