Access The Base Class Method With Derived Class Objects

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 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))

You might also like