Inheritance Puzzle in ASP.NET


In this article I am going to discuss one programme that clear the concept of override and use of new keyword in subclasses using ASP.NET.

In this article I am going to discuss one programme that clear the concept of override and use of new keyword in subclasses using ASP.NET.



public Class A
{
public void printMessage()
{
Console.WriteLine("In Class A");
}
}

public Class B : A //Class B inherits all properties of A
{
public void override printMessage()
{
Console.WriteLine("In Class B");
}
}

public Class C : B //Class C inherits all properties of B
{
public void new printMessage()
{
Console.WriteLine("In Class C");
}

}

public Class MainDemo
{
public static void Main()
{
A objA=new C();
objA.printMessage();
}
}


Output will be
In Class B

How It Will Come let's See

I m having class A that's having function called printMessage..

Class B inherit all properties of class A.and override the method printMessage.Agian Class C will inherits all properties of Class B,and Also Class A is a super Class for C.

Class A Method Print In Class A

override means i do not want new memory slot..so
Class B override the Method printMessage

now we have one memory slots for Class A and B.if You Call That memory slot Method will Print In Class B.

now look at Class C
Class C Declare Method with new Keyword ...new Keyword allocate the memmory dynamically ..So Class C have another Memory Slot and if You call That Memory Slot Then Method Will Print In Class C

Summary

We Have Two Memory slots

first One Having In Class B the instance of A and B Will Point This Slot.we call it as SlotAB.

Second One Having In Class Cthe Instance of C will Point This Slot.
we call it as SlotC



Now let's look at Programme

A objA=new C();

you have Declare instance of A.As we know there are two Slots slotsAB and SlotC.the variable is type of A.so that it will point To SlotsAB.
and Note that Class A is a Super Class of Class C so inheritance rule applies on C.
Now Come To the Calling part ..instance of A point to SlotAB.and SlotAB having a Method Which will Print In Class B.

so if you call the Method objA.printMethod() it will Print In class B

Thanks,

hayat


Comments

Guest Author: Amarjeet30 May 2012

Thanks dude.. it helped me a lot as i am a novice in dot net community...



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: