Method Hiding
Method Hiding:
In
some situation we may want to have a method in the base class which can be
implemented in the derived class independent of the method in the base class
i.e we may want to have its new version altogether
In
the following code i add a method Hello() in the base class and in the derived
class give a completely new definition to the same method by preceding it with
'new' keyword
using
System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
public class VirtualDemo
{
public virtual double Area(double r)
{
return r * r;
}
public void Hello()
{
Console.WriteLine("Hello in Base Class");
}
}
public class A : VirtualDemo
{
public override double Area(double r)
{
double p = 3.142;
return base.Area(r) * p;
}
public new void Hello()
{
Console.WriteLine("Hello in Derived Class");
}
}
public class Test
{
public static void Main(string[] args)
{
A obj1 = new A();
Console.WriteLine(obj1.Area(3));
obj1.Hello();
Console.ReadLine();
}
}
}
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
public class VirtualDemo
{
public virtual double Area(double r)
{
return r * r;
}
public void Hello()
{
Console.WriteLine("Hello in Base Class");
}
}
public class A : VirtualDemo
{
public override double Area(double r)
{
double p = 3.142;
return base.Area(r) * p;
}
public new void Hello()
{
Console.WriteLine("Hello in Derived Class");
}
}
public class Test
{
public static void Main(string[] args)
{
A obj1 = new A();
Console.WriteLine(obj1.Area(3));
obj1.Hello();
Console.ReadLine();
}
}
}
Output:
28.278
Hello in Derived Class
Hello in Derived Class
KeyPoints:
~if
any class method doesnot have 'virtual','abstract' or 'override' keyword and we
attempt to have its new implementation in any derived class a warning is generated to supply
'new' keyword to the method in the derived class.We can also
not override that class method unless that method has 'virtual' keyword
That
was in brief about Method Overriding. In case of any query ask me on the same
blog. In my next article i will explain Abstract Classes and Interfaces with
examples and how these all concepts relate to each other and differ from each
other with similar and even better approach.
Ask
me if you have any query so far after reading the article.
Comments
Post a Comment