Overriding Vs Shadowing in C#


Overriding

Under overriding, you can define a behavior that's specific to the subclass type, which means a subclass can implement a parent class method based on its requirement.

Let us see an example of abstract classes that implements Overriding −

Example

using System;

namespace PolymorphismApplication {
   abstract class Shape {
      public abstract int area();
   }

   class Rectangle: Shape {
      private int length;
      private int width;

      public Rectangle( int a = 0, int b = 0) {
         length = a;
         width = b;
      }

      public override int area () {
         Console.WriteLine("Rectangle class area :");
         return (width * length);
      }
   }

   class RectangleTester {
      static void Main(string[] args) {
         Rectangle r = new Rectangle(10, 7);
         double a = r.area();
         Console.WriteLine("Area: {0}",a);
         Console.ReadKey();
      }
   }
}

Shadowing

Shadowing is also known as method hiding. The method of the parent class is available to the child class without using the override keyword in shadowing. The child class has its own version of the same function.

Use the new keyword to perform shadowing and to create the own version of the base class function.

Let us see an example −

Example

using System;
using System.Collections.Generic;

class Demo {
   public class Parent {
      public string Display() {
         return "Parent Class!";
      }
   }
   
   public class Child : Parent {
      public new string Display() {
         return "Child Class!";
      }
   }

   static void Main(String[] args) {
      Child child = new Child();
      Console.WriteLine(child.Display());
   }
}

Updated on: 21-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements