Overrideing polymorphism – c#

Overrideing is also similar to overloading (sometimes it can be called the same thing since you are overloading/polymorphism functions and classes).

Polymorphism is when you implement functions that are defined in the base class, overriding is when you over ride a base class function.

But with Overrideing classes in c# you can override functions from the base class that are declared as virtual. Virtual means that they are capable of being overridden in a inherited class, so that incase someone tries to call a method of a same name in a subclass then the base class is still called e.g. sometimes better using code and output to show more than what words can say.

Here is not using the virtual keyword in the base class, so that when you try to call the subclasses same method it still goes to the base class.

using System;
 
namespace polymorphism
{
	class Shape {
		public void printName()
		{
			Console.WriteLine("Shape base class");
		}
	}
 
	class Circle : Shape {
		public new void printName()
		{
			Console.WriteLine("Circle class");
		}
	}
 
	class Rectangle : Shape {
		public new void printName()
		{
			Console.WriteLine("Rectangle class");
		}
	}
 
	class Line : Shape {
		public new void printName()
		{
			Console.WriteLine("Line class");
		}
	}
 
	class MainClass
	{
		public static void Main(string[] args)
		{
			Shape[] shapesArray = new Shape[4];
			shapesArray[0] = new Shape();
			shapesArray[1] = new Circle();
			shapesArray[2] = new Rectangle();
			shapesArray[3] = new Line();
 
			foreach (Shape shape in shapesArray)
			{
				shape.printName();
			}
		}
	}
}

output would

Shape base class
Shape base class
Shape base class
Shape base class

but with the

virtual -  override

keywords.

The code

using System;
 
namespace polymorphism
{ 
	class Shape {
		public virtual void printName()
		{
			Console.WriteLine("Shape base class");
		}
	}
 
	class Circle : Shape {
		public override void printName()
		{
			Console.WriteLine("Circle class");
		}
	}
 
	class Rectangle : Shape {
		public override  void printName()
		{
			Console.WriteLine("Rectangle class");
		}
	}
 
	class Line : Shape {
		public override  void printName()
		{
			Console.WriteLine("Line class");
		}
	}
 
	class MainClass
	{
		public static void Main(string[] args)
		{
			Shape[] shapesArray = new Shape[4];
			shapesArray[0] = new Shape();
			shapesArray[1] = new Circle();
			shapesArray[2] = new Rectangle();
			shapesArray[3] = new Line();
 
			foreach (Shape shape in shapesArray)
			{
				shape.printName();
			}
		}
	}
}

As expected the printName() function was called from the subclasses, because of the virtual keyword.

Shape base class
Circle class
Rectangle class
Line class

One thought on “Overrideing polymorphism – c#”

Leave a Reply

Your email address will not be published.