© Adam L. Davis 2020
A. L. DavisModern Programming Made Easyhttps://doi.org/10.1007/978-1-4842-5569-8_8

8. Inheritance

Adam L. Davis1 
(1)
Oviedo, FL, USA
 

Inheritance is a good way to share functionality between objects. When a class has a parent class, we say it inherits the fields and methods of its parent.

In Java, you use the extends keyword to define the parent of a class. For example:
1   public class Griffon extends FlyingCreature {
2   }
Another way to share functionality is called composition . This means that an object holds a reference to another object and uses it to do things. For example, see the following Griffon and Wing classes:
1   class Griffon {
2       Wing leftWing = new Wing()
3       Wing rightWing = new Wing()
4       def fly() { ...

Get Modern Programming Made Easy: Using Java, Scala, Groovy, and JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.