जगदीश खोलिया: Access the base class method with derived class objects (when using shadowing)

Monday, May 14, 2012

Access the base class method with derived class objects (when using shadowing)

When you are using shadowing if you want to access the base class method with derived class objects how can you access it?

First cast the derived class object to base class type and if you call method it invokes base class method.Please note that it works only when derived class method is shadowed.
observe the bold lines below:

public class BaseClass
{
public void Method1()
{
string a = "Base method";
}
}
public class DerivedClass : BaseClass
{
public new void Method1()
{
string a = "Derived Method";
}
}
public class TestApp
{
public static void main()
{
DerivedClass derivedObj = new DerivedClass();
BaseClass obj2 = (BaseClass)derivedObj;
obj2.Method1(); // invokes Baseclass method

}
}
Post a Comment