Monday, April 3, 2023

How to implement polymorphism in .net? Explain Interface Polymorphism and Method Overloading.

Polymorphism is the ability of an object to take on many forms. In .NET, polymorphism can be implemented through the use of interfaces and method overriding.

Interfaces:
An interface is a contract that defines a set of methods and properties that a class must implement. Interfaces are declared using the "interface" keyword and can be implemented by any class.
For example, let's say we have an interface called "IAnimal" that defines a method called "MakeSound()". Any class that implements the IAnimal interface must provide an implementation of the MakeSound() method.

interface IAnimal {
   void MakeSound();
}


We can then create classes that implement the IAnimal interface and provide their own implementation of the MakeSound() method. For example:

class Dog : IAnimal {
   public void MakeSound() {
      Console.WriteLine("Bark");
   }
}

class Cat : IAnimal {
   public void MakeSound() {
      Console.WriteLine("Meow");
   }
}



Method Overriding: Method overriding is the process of providing a new implementation of a method in a derived class that overrides the implementation of the same method in its base class.
For example, let's say we have a base class called "Shape" that defines a virtual method called "CalculateArea()". The Circle and Rectangle classes inherit from the Shape class and provide their own implementation of the CalculateArea() method.

class Shape {
   public virtual double CalculateArea() {
      return 0.0;
   }
}

class Circle : Shape {
   public override double CalculateArea() {
      // Implementation of the CalculateArea method for Circle class
   }
}

class Rectangle : Shape {
   public override double CalculateArea() {
      // Implementation of the CalculateArea method for Rectangle class
   }
}




When a method is called on an object, the implementation of the method that is executed depends on the actual type of the object at runtime. For example:

Shape shape = new Circle();
double area = shape.CalculateArea(); // Calls the CalculateArea method of the Circle class


In this example, the CalculateArea() method of the Circle class is called, even though the variable shape is declared as a Shape type. This is because the actual type of the object at runtime is a Circle, which overrides the implementation of the CalculateArea() method in the Shape class. This is an example of polymorphism in action.
 

 

 

 

No comments:

Post a Comment

Please keep your comments relevant.
Comments with external links and adult words will be filtered.