Sie sind auf Seite 1von 1

Access the base class method with derived class objects

View(s):
28684

When you are using shadowing if you want to access the base class method with derived class objects how can you access it?
Answer 1)
1st cast the derived class object to base class type and if you call method it invokes base class method. Keep in mind it works only when derived class method is shadowed.
observe the highlighted 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
}
}
Asked in: Mahindra Satyam Expertise Level: Intermediate
Last updated on Tuesday, 24 July 2012

Copyright 2009 - 2012 mr-ponna.com

3/5 stars (21 vote(s))

Das könnte Ihnen auch gefallen