Search

Aug 9, 2008

Parent can hold reference of Child

Hello all,

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);
}
}
You can see the virtual method; this is the key thing to see the power of A a = new B();.

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
There is nothing wrong in it, it can easily understood.

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();
}
See the signature of this method, it says private static void CallMe(A a), the parameter is object of class A; that is PARENT. And inside it the first line is setting the property of parent and then based on the type the rest of properties is getting populated. And at the end calling PrintMe which is virtual so based on reference it will call the method.

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
1st line creating object of B and setting it to A'a object. 2nd linke calling CallMe by passing the parent object. This will first set the property of child and then as its B's object will set the property of Name and call PrintMe, which give call to B's PrintMe method [remember virtual].

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:

Anonymous said...

Great!!!!