[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 240
  • Last Modified:

Inheritance explanations

Hello

Can you explain to me why the following console app produces the results it produces? I just want you to explain how inheritance works with these 2 classes.

class A
{
   public void F() { Console.WriteLine("A.F"); }
   public virtual void G() { Console.WriteLine("A.G"); }
}
class B: A
{
   new public void F() { Console.WriteLine("B.F"); }
   public override void G() { Console.WriteLine("B.G"); }
}
class Test
{
   static void Main() {
      B b = new B();
      A a = b;
      a.F();
      b.F();
      a.G();
      b.G();
   }

Thank you
0
Kokas79
Asked:
Kokas79
  • 2
1 Solution
 
RoninTheCommented:
static void Main() {
      B b = new B();
      A a = b;

>>> statements :  A a = new A(); B b =a; aren't valid because derived class (Class B) can have additional members/methods over its Base class(class A).

      a.F();
>>> control goes to Class A's F() because, there exists two F(), one in class A, other in class B ("new" keyword). any call fom class A instance is passed to the class A level function.

      b.F();
>>> same goes here. control goes to class B level function.

      a.G();
>>> here there aren't two G(). rather there is only one G(), which has been overridden in the derived class. And since variable 'a' has been assigned 'b' (ie  A a = b;) which is of class B type, control goes to B->G().
 
      b.G();
>>> class B variable, gives the obviouss result.

   }
0
 
Kokas79Author Commented:
What i dont understand is a.F()

We are creating an object of type B...right? there is only one new keyword. Then does A a = b mean that we just have a variable of type A that points to object B on the heap?
so the object B decides to implement the base method because the variable is of type A?
0
 
RoninTheCommented:
>so the object B decides to implement the base method because the variable is of type A?

yeah, essentially yes. This behaviour is called "polymorphism" in oop. The method to be implemented is decided on the basis of the type of the object.
go thru following link for more on this..
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dndotnet/html/interinher.asp
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now