Get startedGet started for free

Propagating Functionality with Inheritance

1. Propagating Functionality with Inheritance

Here we have a new fancy microwave with extra features.

2. microwave

Recall that the original microwave from last chapter had four pieces of functionality. You could open and close the door, set the power level, and cook some food. If you want to define an R6 class for the fancy microwave, you could just copy and paste the definition from the original microwave, and then start adding new features. Unfortunately, copying and pasting is a really big source of bugs, and is usually a sign that you are writing bad code. If you change the definition of the original microwave, you really want a way for those changes to automatically be mirrored in the fancy microwave. R6 achieves this through the concept of

3. thing_factory

inheritance. Let's take a look at how it works. Here's the pattern for an R6 class. To create a class that inherits from this class, you use

4. parent

the inherit argument. The classes that inherit from the original are called child classes. The original class is called the parent of the child classes.

5. child_thing_factory

Here you see a Child Thing that inherits from the Thing class. All of the data and functionality of the parent class is passed on to the child. That is, all the fields from the private, public, and active elements. So without defining anything extra, the Child Thing already has two private data fields and a method. You can add any additional functionality that you like to the child. Now the child class has everything that the parent has, and an extra method. The important thing to remember is that inheritance only works in one direction. If you are a parent,

6. children

this will probably sound familiar. Children take everything from their parent, but the parent doesn't get anything back.

7. parent-child

When you talk about the relationship between the microwaves, you can say that a fancy microwave is a microwave, but the converse doesn't hold. It wouldn't be true to say that any microwave

8. parent-child

is a fancy microwave. This translates into how classes are ascribed to R6 objects.

9. a_thing

The class of a thing is a character vector of "Thing" and "R6". That is, the thing object inherits from "Thing" and it inherits from "R6".

10. a_child_thing

The class of the child thing also includes "ChildThing".

11. Summary

To summarize, you can propagate functionality from one class to another using inheritance. This is achieved by using the inherit argument of R6Class. The child class gets all the data fields and functions from the parent class, but the converse is not true. That is, the parent class does not inherit the traits of its child.

12. Let's practice!