Lyon Gu
Lyon Gu

Reputation: 23

Questions about .Net inheritance

public class Father
{
  // static string TYPE = "FATHER";
    public Father()
    {
        //Console.WriteLine("ctor");
    }
    public virtual void Print()
    {
        Console.WriteLine("I'm father");
    }
}

public class Son:Father
{
    public override void Print()
    {
        base.Print();
        Console.WriteLine("I'm son");
    }
}

As we konw, if we call Son.Print(),It'll print out "I'm father" and "I'm son".And Father.Print() is an instance method ,we need to create an instance first.So that's the question,who creates it?Obviously,not me... Or Son owns two Print methods in the methodtable.One of them can be accessed by Father,anthor can be accessed by itself? Which one is right?Or neither is right?Please tell me!Thanks!

Upvotes: 1

Views: 163

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

Who creates it? Obviously not me

What makes you so sure? Of course you do:

Son s = new Son();

Or Son owns two Print methods in the methodtable.

No, it has just one Print method, but it has something else: it knows about its base class, Father, which has its own Print method. That's why Son has access to two Prints - its own and his Father's.

Upvotes: 4

Related Questions