0

I have a base abstract class that implements Method1

    abstract class Base
    {
        public void Method1()
        {
            Console.WriteLine("Method1 Base");
        }

        public abstract void Method2();
    }

and a base2 abstract class that inherits from base and hide Method1

    abstract class Base2 : Base
    {
        public new abstract void Method1();
    }

and a concrete class that inherits from base2 and implements Method1

    class Concrete : Base2
    {
        public override void Method1()
        {
            Console.WriteLine("Method1 Concrete");
        }

        public override void Method2()
        {
            Console.WriteLine("Method2 Concrete");
        }
    }

Now I have 2 cases in the programme and I was expecting the same result, that the Method1 form the concrete class get called, but in the first case the Method1 form the base class get called. I dont understand why because I am instantiating objects with new Concrete()

    class Program
    {
        static void Main(string[] args)
        {

            Base obj1 = new Concrete();
            obj1.Method1(); //output: "Method1 Base" why????
            obj1.Method2(); //output: "Method2 Concrete"

            Concrete obj2 = new Concrete();
            obj2.Method1(); //output: "Method1 Concrete"
            obj2.Method2(); //output: "Method2 Concrete"

        }
    }
med morad
  • 497
  • 4
  • 12
  • 5
    Becode `Method1` in `Base` is not abstract (so virtual) nor virtual (implemented here), thus calling it from an instance of type `Base` call it: there is no polymorphism available here. Polymorphism for it is only available starting from `Base2` and childs, even if reference is of type `Base2`. –  Jan 26 '21 at 14:20
  • 3
    Without virtuality (using virtual methods tables), no polymorphism: it is impossible to create and to know how to call overrided methods in child classes to be called by only knowing the type of a base class. Virtuality and so polymorphism begin with using `abstract` or `virtual` keywords. –  Jan 26 '21 at 14:28
  • 1
    If you declare `Method1` `virtual` in `Base`, you can still declare it `override abstract` in `Base2` (but not `new`) and thus force `Concrete` to provide an implementation different to `Base`s - is that what you were aiming for? In such a case, all 4 lines output `Concrete`. – Damien_The_Unbeliever Jan 26 '21 at 14:38
  • 3
    Thank you for you answers, I think I understand polymorphisme a little bit more now, and the some more differences between java and C#... I found this https://stackoverflow.com/questions/27957424/base-method-hiding-in-c-sharp-and-java and it clarify more my misunderstanding. – med morad Jan 26 '21 at 14:44

0 Answers0