简体   繁体   中英

accessing overridden method from derived class object

Is it possible to access the method that has been overridden using the object of the derived class?

using System;


class Bclass
{
    public virtual int result(int a,int b)
    {
        return a + b;
    }
}
class Dclass:Bclass
{
    public override int result(int a, int b)
    {
        return a - b;
    }
}

public class Program
{

    static public void Main(string[] args)
    {
        Dclass obj1 = new Dclass();
        Console.WriteLine(obj1.result(10, 5));
    }

}

Is there a way to get the output as 15?

From MSDN documentation:

The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event.


override modifier are designed to extend functionality of virtual function. When ever you call overridden function with the help of derived class object it will call overridden function.

To answer your question,

Is it possible to access the method that has been overridden using the object of the derived class?

  • There is no way to call virtual method directly using derived class object

Ways to call virtual method:

Approach 1:

Create a new function in derived class and call base.result() from it.

public int BaseResult(int a, int b)
{
    return base.result(a, b);
}

and call BaseResult() using derived class instance

  Dclass obj1 = new Dclass();
  Console.WriteLine(obj1.BaseResult(10, 5));

Try it online

Approach 2:

Create instance of base class and from that access virtual method.

    Bclass obj2 = new Bclass();
    Console.WriteLine(obj2.result(10, 5));

Unless you need to declare the base method as virtual for some reason, you could also achieve what you want by declaring the derived class method as new , thereby hiding the implementation when using it through an instance of the derived class.

At the same time, you can still access the base implementation by casting the object to the base class.

Following the example you provided:

class Bclass
{
    public int result(int a,int b)
    {
        return a + b;
    }
}

class Dclass : Bclass
{
    public new int result(int a, int b)
    {
        return a - b;
    }

    public int BaseResult(int a, int b)
    {
        return base.result(a, b);
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        Dclass obj1 = new Dclass();
        Console.WriteLine(((Bclass)obj1).result(10, 5)); // 15
    }
}

More information about the differences between override and new can be found in this MSDN article .

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