We all know that A a = new B(); we learn this by heart from the day we start OOPS.
But there are lots many people who just do cramming lolz, I have one good example which helps you to get your mind set what is meaning of A a = new B();
We all know that using virtual function we can achive the golden word "Parent can hold reference of child", but its not just virtual function involved, there are also reusability.
Lets say you have one base class having 10 properties and you derived 2 more classes which individual has more then 5-5 properties.
So what I do? Should I create methods for each child class? What if I have more 2-3 class?? The answer is NO [I knew that you know it :)]
So what to do? How A a = new B(); will help full here?
Lets learn with example.
I am haivng A as parent class and B, C as child class.
class A
{
public int Id { get; set; }
public virtual void PrintMe()
{
Console.WriteLine("Id : " + Id);
}
}
class B : A
{
public string Name { get; set; }
public override void PrintMe()
{
base.PrintMe();
Console.WriteLine("Name : " + Name);
}
}
class C : A
{
public string Company { get; set; }
public override void PrintMe()
{
base.PrintMe();
Console.WriteLine("Company : " + Company);
}
}
Now the method call, here is the code to calling method PrintMe
A a = new B();
a.PrintMe(); //will call B method
a = new A();
a.PrintMe(); //Will call A method
a = new C();
a.PrintMe(); //Will call C method
Now our purpose, what is it? Yes we need to set properties and then call PrintMe method.
private static void CallMe(A a)
{
a.Id = 4;
if (a is C)
((C)a).Company = "My Company";
else if (a is B)
((B)a).Name = "My Name";
a.PrintMe();
}
Lets call method CallMe.
1. a = new B();
2. CallMe(a); //Will print Id and Name
3. a = new C();
4. CallMe(a); //Will print Id and Company
So, this is the real world use of A a = new B();
Hope you understand, any question any query please feel free to approch me.
1 comment:
Great!!!!
Post a Comment