Reputation: 709
I have the following classes in my program and now I want to access the method M2() present in the class Y. I tried to access it by creating the object of class Z and then casting it with variable of class X and calling x.M2(10,5) but instead of class Y it is still invoking the method M2() present in the class X. Thanks.
public partial class Abstract_Class : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Z z = new Z();
int r1 = z.M2(10, 20); //gives output -20
X x = z;
int r2 = x.M2(10,5); //gives output 10 while I want it to print 15
}
}
public class W
{
public virtual int M2(int x, int y)
{
return x - y;
}
}
public abstract class X : W
{
public abstract void M1();
public override int M2(int x, int y)
{
return 2*(x-y);
}
}
public abstract class Y : X
{
public sealed override int M2(int x, int y)
{
return 3 * (x - y);
}
}
public class Z : X
{
public override void M1()
{
}
}
Upvotes: 0
Views: 1229
Reputation: 23208
You would need to create an instance of Y
. Since it's abstract
, you would have to create some subclass of it.
public class SubY : Y
{
}
Then in your code write something like:
var suby = new SubY();
int r2 = suby.M2(10, 5); //15
Upvotes: 2