This is a basic thing but can be quite confusing also!! Let me give a try to explain this….

Methods without definitions in base class (are basically abstract methods) and
must be implemented in derived class with “override” keyword. The “new” keyword cannot be used here.

A method with definition in base class is normal (which doesn’t have “virtual” keyword)
There is no need to override/hide it in the derived class.
But it “can” be hidden in derived class with “new” keyword

Consider a method with definition in base class which has “virtual” keyword, this “can” be overridden in derived class with “override” or hidden using “new” keyword.

Overriding Vs Hiding

When an reference of abstract class contains instance of the derived class
and an method found in both classes is called, then here we can note a difference in it.

New keyword simply hides the method in base class.
So its actually present and can be called from a reference of the base class.

But override overwrites the method in base class.
So a overridden method in base class is not called when called from a reference of a base class.

Note this example:


using System;

namespace aruns_code
{
abstract class abs
{

	// A method without definition in base class is abstract
	// and should be implemented in derived class
	// with "override" keyword
	public abstract void absMethod();

	public void nonAbs()
	{
		Console.Write("inside nonAbs of abs\n");
	}

	public virtual void nonAbs2()
	{
		Console.Write("inside nonAbs2 of abs\n");
	}
}

class der : abs
{
	public override void absMethod()
	{
		Console.Write("inside absMethod of der\n");
	}

	// A method with definition in base class is normal one
	// and can be overridden in derived class with new keyword
	public new void nonAbs()
	{
		Console.Write("inside nonAbs of der\n");
	}

	// A method with definition in base class is normal
	// but has virtual keyword
	// and "may" be overridden in derived class
	//with "override" or "new" keyword
	public override void nonAbs2()
	{
		Console.Write("inside nonAbs2 of der\n");
	}
}

class testHiding
{
	[STAThread]
	static void Main(string[] args)
	{
		abs absObj = new der();
		absObj.absMethod();
		absObj.nonAbs();
		absObj.nonAbs2();
	}
}
}

/*

OUTPUT IS :

inside absMethod of der
inside nonAbs of abs
inside nonAbs2 of der
Press any key to continue 

 */

So you got it. If you still did not get it, then please put a comment below. I will get back to you !!

Advertisement