Abstract Classes with new and override keywords
Different senario's where we have use the
Abstract Classes with new and override keywords. This article the implementation of abstract class
with virtual with new and override keyword. This example show the virtual and overrides to accomplish Method overriding. Differentiate virtual and new to accomplish Method hiding.
Find Abstract Classes with new and override keywords
Here is an example which shows and diffentiate the use of virtual with new
and virtual with override keywords.
ex-1
abstract class Shape
{
public Shape()
{
System.Console.WriteLine("Shape");
}
public void draw()
{
System.Console.WriteLine("Drawing Shape");
}
}
class Triangle : Shape
{
public Triangle()
{
System.Console.WriteLine("Triangle");
}
public void draw()
{
System.Console.WriteLine("Drawing Triangle");
}
}
How the base and derived class will be allocated in the memory
o/p when there is no keywords are used
there will be a Warning saying Consoleapplication1.triangle.draw() hides inherited member consoleapplication1.shape.draw() use new keyword if hiding was intended
ex-2 Virtual - override
abstract class Shape
{
public Shape()
{
System.Console.WriteLine("Shape");
}
public virtual void draw()
{
System.Console.WriteLine("Drawing Shape");
}
}
class Triangle : Shape
{
public Triangle()
{
System.Console.WriteLine("Triangle");
}
public override void draw()
{
System.Console.WriteLine("Drawing Triangle");
}
}
class Abstractexample
{
static void Main()
{
//Shape m = new Shape(); // Cannot create an instance of the abstract class CSharpExample.Shape
Triangle t1 = new Triangle();
Shape t3 = new Triangle();
System.Console.WriteLine("\n\nNow Drawing Objects\n");
t1.draw();
t3.draw();
System.Console.WriteLine("\n");
Console.ReadLine();
}
}
derived class draw method will override the base draw method there will be internally only one draw method in the derived class.
o/p
ex-3 virtual with new
abstract class Shape
{
public Shape()
{
System.Console.WriteLine("Shape");
}
public virtual void draw()
{
System.Console.WriteLine("Drawing Shape");
}
}
class Triangle : Shape
{
public Triangle()
{
System.Console.WriteLine("Triangle");
}
public override void draw()
{
System.Console.WriteLine("Drawing Triangle");
}
}
class Abstractexample
{
static void Main()
{
//Shape m = new Shape(); // Cannot create an instance of the abstract class CSharpExample.Shape
Triangle t1 = new Triangle();
Shape t3 = new Triangle();
System.Console.WriteLine("\n\nNow Drawing Objects\n");
t1.draw();
t3.draw();
System.Console.WriteLine("\n");
Console.ReadLine();
}
}
derived class draw method will hides the base draw method there will be internally only one draw method in the derived class.
o/p