简体   繁体   中英

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!

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 Print s - its own and his Father 's.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM