Hiding Base Class Members

Hiding Base Class Members
Sometimes derived class members have the same name as a corresponding base class member. In this case, the derived member is said to be "hiding" the base class member.
When hiding occurs, the derived member is masking the functionality of the base class member. Users of the derived class won't be able to see the hidden member; they'll see only the derived class member. The following code shows how hiding a base class member works.
abstract public class Contact
{
private string address;private string city;private string state;private string zip;public string FullAddress()
{
string fullAddress =address + '\n' +city + ',' + state + ' ' + zip;return fullAddress;
}
}
public class SiteOwner : Contact
{
public string FullAddress()
{
string fullAddress;// create an address...return fullAddress;
}
}
In this example, both SiteOwner and its base class, Contact, have a method named FullAddress(). The FullAddress() method in the SiteOwner class hides the FullAddress() method in the Contact class. This means that when an instance of a SiteOwner class is invoked with a call to the FullAddress() method, it is the SiteOwner class FullAddress() method that is called, not the FullAddress() method of the Contact class.

Although a base class member may be hidden, the derived class can still access it. It does this through the base identifier. Sometimes this is desirable. It is often useful to take advantage of the base class functionality and then add to it with the derived class code. The next example shows how to refer to a base class method from the derived class.
abstract public class Contact
{
private string address;private string city;private string state;private string zip;public string FullAddress()
{
string fullAddress =address + '\n' +city + ',' + state + ' ' + zip;return fullAddress;
}
}
public class SiteOwner : Contact
{
public string FullAddress()
{
string fullAddress = base.FullAddress();// do some other stuff...return fullAddress;
}
}
In this particular example, the FullAddress() method of the Contact class is called from within the FullAddress() method of the SiteOwner class. This is accomplished with a base class reference. This provides another way to reuse code and add on to it with customized behavior.
Category: , 0 comments

Leave a comment