Implementing Inheritance

Inheritance involves a base class and a derived class. The derived class inherits from the base class. With few exceptions, members of the base class are inherited into the derived type. Derived classes can override inherited members and add new members to extend the base class.

Here is the inheritance syntax:

class derivedclass: baseclass, interface1, interface2, ...,  interfacen {
    body
}

In the class header, the inheritance operator (:) indicates inheritance and is followed by the inheritance list. The inheritance list is a comma-delimited list that includes a maximum of one base class and any number of interfaces. Classes are limited to inheriting a single class. However, a class can implement multiple interfaces. C++ developers are familiar with multiple base-class inheritance. Omitting this feature from C# was an important design decision. First, multiple inheritance was never that popular. Second, multiple inheritance often causes more problems than it resolves. Third, multiple inheritance introduces the potential for member ambiguity.

A base type must have the same or greater accessibility as the derived type. A compiler error occurs in the following code because the accessibility of the base class is narrower than the derived class, which is an error:

internal class ZClass {
}
public class YClass : ZClass { // Error
}

.NET supports only public inheritance. C++ supports public, protected, and private inheritance. Despite this flexibility in C++, practically all inheritance is public inheritance. Most C++ developers were not familiar with or ever used any other kind of inheritance. Thus, protected and private inheritance probably will not be missed.

Accessibility

Accessibility sets the visibility of members to the outside world and to derived types. Members are always visible in the current or containing type. Table 3-3 describes member accessibility.

Table 3-3. Member accessibility

Member access modifier

Outside world

Derived class

public

Yes

Yes

private

No

No

protected

No

Yes

internal

Yes (this assembly)

Yes (this assembly)

internal protected

Yes (this assembly)

Yes

Are private members of the base class inherited? Private members indeed are inherited, but they are not visible or directly accessible in the derived class. These members are accessible through the public and protected functions also inherited from the base class. Therefore, a derived type has two realms of private members. One realm includes private members that are defined in a derived class. These members are visible in the derived type. The other realm includes inherited private members, which are not visible to the derived type.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.9.169