Override hide the base class of new override method

  • 2020-05-09 19:10:08
  • OfStack


public class Father
    {
        public void Write() {
            Console.WriteLine(" The father ");
        }
    }
    public class Mother
    {
        public virtual void Write()
        {
            Console.WriteLine(" The mother ");
        }
    }
    public class Boy : Father
    {
        public new void Write()
        {
            Console.WriteLine(" The child ");
        }
    }
    public class Girl : Mother
    {
        public override void Write()
        {
            Console.WriteLine(" female ");
        }
    }


static void Main(string[] args)
        {
            Father father = new Boy();
            father.Write();
            Boy boy = new Boy();
            boy.Write();

            Mother mother = new Mother();
            mother.Write();
            Girl girl = new Girl();
            girl.Write();
            Console.ReadLine();
        }

Output:

The father
The child
The mother
female

Add a call to the parent method:


public class Boy : Father
    {
        public new void Write()
        {
            base.Write();
            Console.WriteLine(" The child ");
        }
    }
    public class Girl : Mother
    {
        public override void Write()
        {
            base.Write();
            Console.WriteLine(" female ");
        }
    }

Output:

The father
The father
The child
The mother
The mother
female

As you can see, new and override are the same on the results of the program.


Related articles: