Embrace, Extend, Override

Object-Oriented Programming with S3 and R6 in R

Richie Cotton

Data Evangelist at DataCamp

Object-Oriented Programming with S3 and R6 in R
thing_factory <- R6Class(
  "Thing",
  public = list(
    do_something = function() {
      message("the parent do_something method")
    }
  )
)
Object-Oriented Programming with S3 and R6 in R
child_thing_factory <- R6Class(
  "ChildThing",
  inherit = thing_factory,

public = list( do_something = function() { message("the child do_something method") },
do_something_else = function() { message("the child do_something_else method") }
)
)
Object-Oriented Programming with S3 and R6 in R
a_child_thing <- child_thing_factory$new()
a_child_thing$do_something()
the child do_something method
Object-Oriented Programming with S3 and R6 in R

 

 

private$ accesses private fields

self$ accesses public methods in self

super$ accesses public methods in parent

Object-Oriented Programming with S3 and R6 in R
child_thing_factory <- R6Class(
  "ChildThing",
  inherit = thing_factory,
  public = list(
    do_something = function() {
      message("the child do_something method")
    },
    do_something_else = function() {
      message("the child do_something_else method")

self$do_something()
super$do_something()
} ) )
Object-Oriented Programming with S3 and R6 in R

 

a_child_thing <- child_thing_factory$new()
a_child_thing$do_something_else()
the child do_something_else method
the child do_something method
the parent do_something method
Object-Oriented Programming with S3 and R6 in R

Summary

  • Override by giving the same name
  • Extend by giving a new name
  • self$ accesses public methods in self
  • super$ accesses public methods in parent
Object-Oriented Programming with S3 and R6 in R

Let's practice!

Object-Oriented Programming with S3 and R6 in R

Preparing Video For Download...