5.1 Inheritance
Inheritance allows a class to extend and reuse behavior defined in its ancestor class (superclass). Java and C# support only single class inheritance, in which a given class can inherit from only one other class. This is in contrast to C++, which allows a class to inherit behavior from multiple classes.
Inheritance creates an is-a relationship between the subclass and the superclass; in other words, a subclass is a type of the superclass. Because of the single class inheritance in Java and C#, you must be careful in choosing which class to inherit your class from. For example, if you have a custom maplike data structure, should you inherit from java.util.HashMap? Doing so would instantly make your data structure a java.util.HashMap, but suppose that in the future you want to maintain the order in which you put the key-value entries in your map. In that case, you would have rewrite your class because java.util.HashMap does not maintain the order in which key-value entries are put in it.
Inheritance is a useful mechanism for leveraging and extending an existing code base. Exactly which class members can be inherited from a superclass depends on the access modifiers used on its class members. Later in this chapter we will look at the C# access modifiers that control its inheritance mechanism.
|