Pages

Sunday, 28 June 2015

Masking Members

Masking Members

A derived class cannot delete any of the members it has inherited it can only mask a base class member with a member of the same name. This is extremely useful, and one of the major features of inheritance.

For example, you might want to inherit from a base class that has a particular method. That method, although perfect for the class in which it is declared, may not do exactly what you want in the derived class. In such a case, what you want to do is to mask the base class method with a new member declared in the derived class.

Some important aspects of masking a base class member in a derived class are the following:
  • To mask an inherited data member, declare a new member of the same type and with the same name.
  • To mask an inherited function member, declare a new function member with the same signature. Remember that the signature consists of the name and parameter list, but does not include the return type.
  • To let the compiler know that you’re purposely masking an inherited member, use the new modifier. Without it, the program will compile successfully, but the compiler will warn you that you’re hiding an inherited member.
  • You can also mask static members.
Following code is the example of how to mask a person member.
class person
{
 public string firstName;
 public string lastName;
 public ushort age;

 public void greet()
 {
  Console.WriteLine("Hello "+ firstName + " " + lastName);
 }
 
 public void talk(string words)
 {
  Console.WriteLine(firstName+" "+ lastName + " say "+ words);
 }
}

class student : person
{
 public string school;

 new public void greet()
 {
  Console.WriteLine("Hello " + firstName + " " + lastName);
  Console.WriteLine("I study in " + school);
 }
}

class employee : person
{
 public string company;
 new public void greet()
 {
  Console.WriteLine("Hello " + firstName + " " + lastName);
  Console.WriteLine("I work for " + company);
 }
}

With the same Main method, the program will display:
Hello Yang Sopiana
I work for Company.inc
Hello Zidni Ilman
I study in Elementary School

0 comments:

Post a Comment