Wednesday, March 24, 2010

Hiding Members of the Base Class

We have already used the new operator to create objects. Another use of the new operator is to modify declarations of the inherited members in order to hide members with the same names in the base class. Suppose that we have a base class that contains a method called MyMethod:
public class MyBaseClass
{
    public int myInt;
    public void MyMethod() //MyMethod on the base class
    {
        //….
    }
}
When this class is inherited, the derived class will inherit all its members. Suppose that we would like to declare a new member with the same name, MyMethod, in the derived class. We can do that by using the new modifier, as shown in this example:
public class MyDerivedClass: MyBaseClass
{
    new public void MyMethod() // MyMethod on the derived class
    {
        //…
    }
}
The job of the new modifier here is to hide the member with the same name in the base class. A method that uses the new modifier hides properties, fields, and types with the same name. It also hides the methods with the same signatures. In general, declaring a member in the base class would hide any members in the base class with the same name. If we declare MyMethod in the above example without the new modifier, it still works, but we will get a compiler warning:
‘MyDerivedClass.MyMethod()’ hides inherited member
‘MyBaseClass.MyMethod()’. Use the new keyword if hiding was intended.
Notice the following when we use the new modifier:
•    We cannot use new and override in the same declaration. If we do that we get the compiler error:
A member ‘MyDerivedClass.MyMethod()’ marked as override cannot be marked as new or virtual.
•    It is possible, through, to use virtual and new in the same declaration. This emphasizes our intention to hide the member in the base class and start a new point of specialization in the inheritance hierarchy.

No comments:

Post a Comment