none
How to make call derived class's method from base class RRS feed

  • Question

  • Let me explain the class/method relationship first.

    There is a base class and a derived class inherited from the base class.

    The base class has two method(method 1 & method 2).

    The derived class has a method(method 2)

    The base class's method 2 is called from 1 when a object is instantiated by base class.

    What I want to do is that the derived class's method 2 should be called when a object is instantiated by derived class.

    Is it possible? 

    If so, how to implement it? 



    • Edited by Jeff0803 Friday, September 6, 2019 6:26 PM
    Friday, September 6, 2019 6:08 PM

All replies

  • Put a method in the base class as Protected Abstract and then call it from the base class.

    I have done this before with good success. This is the (trimmed) code from base class.

            protected abstract void ResultWriter();
            private void WriteEverything()
            {
                try
                {
                    ResultWriter();
                }
                finally
                {
                    TryToKillExcel(_ExcelApp, _ResultBook);//Excel is hard to kill programmatically!
                }
            }
    Ethan


    Ethan Strauss

    Friday, September 6, 2019 8:25 PM
  • The base class has two method(method 1 & method 2).

    The derived class has a method(method 2)

    The base class's method 2 is called from 1 when a object is instantiated by base class.

    What I want to do is that the derived class's method 2 should be called when a object is instantiated by derived class.

    This should happen automatically. It is called "polimorphism". For it to work, you need to declare method2 in the base clase as "virtual", and in the derived class as "override". Once you've done this, everything will work as you wish: when you create an instance of the derived class, if method1 calls method2, then the method 2 of the derived class will be executed instead of method 2 of the base class.

    class Parent
    {
        public void Method1()
        {
            Method2();
        }
        protected virtual void Method2()
        {
            ....
        }
    }
    
    class Derived
    {
        protected override void Method2()
        {
            ....
        }
    }
    
    ...
    
    Parent p = new Parent();
    p.Method1(); // This executes Method2 on Parent
    
    Derived d = new Derived();
    d.Method1(); // This executes Method2 on Derived (even though Method1 is located in Parent)



    Friday, September 6, 2019 8:29 PM
    Moderator