Hands-On Design Patterns with Java
上QQ阅读APP看书,第一时间看更新

Inheritance

Inheritance in programming is the same as in real life. A girl inherits from her mother, who inherits from her mother, and so on. The following diagram shows inheritance in the real world and how it relates to OOP:

Inheritance examples

On the left-hand side of the preceding diagram, a Grandmother passes down traits to the Daughter, who passes down traits to the Granddaughter. So, the Granddaughter inherits from both the Daughter and Grandmother. The same inheritance concept applies to our Bicycle class, which inherits from both the Two-Wheeled class and the Vehicle class. This is a powerful schema as it avoids class bloating. As an example, if the Vehicle class has data elements such as year, make, and model, those elements are automatically part of the Two-Wheeled and Bicycle classes. We will see an example of this later on in this chapter.