Inheritance and Name hiding It is possible for a derived class to define a member that has the same name as the member in its base class. When this happens, the member in the base class is hidden within the derived class. While this is not technically an error in C#, the compiler will issue a warning message. This warning alerts you to the fact that a name is being hidden. If your intent is to hide the base class member, then to prevent this warning, the derived class member must be preceded by the new keyword.
Lets see how to access a hidden name using base
General form:
base.member
Here, member can either be a method or an instance variable. This form of base is most applicable to situations in which a member name in a derived class hides a member by the same name in the base class.
For Example:
// Using base to overcome name hiding.
using System; class ABase { public int number = 0; } class BDerived : ABase { new int number; //this 'number' hides the 'number' in ABase.
public BDerived(int a , int b) { base.number = a; //this uncovers the 'number' in ABase number = b; // 'number' in BDerived } public void show() { //this displays 'number' in ABase Console.WriteLine("number in base class: " + base.number);
//this displays 'number' in BDerived Console.WriteLine("number in derived class: " + number); } } class Access { public static void Main() { BDerived derivedclass = new BDerived(1 , 2); derivedclass.show(); Console.Read(); } }
Here’s the output:
number in base class: 1 number in derived class: 2
Although the instance variable number in BDerived hides the number in Abase, base allows access to the number defined in the base class.
Hidden methods can also be called through the use of base Example:
// Using base to overcome name hiding.
using System; class ABase { public int number = 0;
public void show() { Console.WriteLine("number in base class: " + number); } } class BDerived : ABase { new int number; //this 'number' hides the 'number' in ABase.
public BDerived(int a , int b) { base.number = a; //this uncovers the 'number' in ABase number = b; // 'number' in BDerived } new public void show() { base.show(); // this calls the show() in ABase
//this displays 'number' in BDerived Console.WriteLine("number in derived class: " + number); } } class Access { public static void Main() { BDerived derivedclass = new BDerived(1 , 2); derivedclass.show(); Console.Read(); } }
Here’s the output:
number in base class: 1 number in derived class: 2
As you can see, base.show() calls the base class version of show()
Notice that new is used in this program to tell the compiler that you know that a new method called show() is being created that hides the show() in the base class.
|
No responses found. Be the first to respond and make money from revenue sharing program.
|