If I am having base class like below:
class A
{
public virtual void print()
{
Console.WriteLine("Base class method");
Console.Read();
}
}
And derived class which inherited from base class like below:
class B : A
{
public override void print()
{
Console.WriteLine("Child Class Method");
Console.Read();
}
}
Main method to to create the objects is below:
class Method
{
static void Main(string[] args)
{
A obj=new B();
obj.Print();
}
}
The above code will invoke the child class method. But even if I created object like B obj=new B()
and did 'obj.Print()', the same output would be rendered.
So what is the use creating object like A obj=new B()
and calling method like above?
On the other hand, if I change derived class method as below:
public new void print()
{
Console.WriteLine("Child Class Method");
Console.Read();
}
And if do A obj=new B()
, then obj.print()
will invoke the base class method. The same if I do A obj=new A()
and obj.print()
.
So what is the point of having a base class reference variable pointing to a derived reference class object and invoking the members like above? At which scenarios should this logic be used?