If I am using shadowing and if I want to access base class method with derived class objects, how can I access it?
In C++, a derived class object can be assigned to a base class object, but the other way is not possible.
Derived class can not access the private members of it's base class. No type of inheritance allows access to private members.
Use the base
keyword:
base.MethodOnBaseClass();
The base keyword is used to access members of the base class from within a derived class:
First 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.
For Example,
Observe the commented 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; // cast to base class
obj2.Method1(); // invokes Baseclass method
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With