I wrote an article in the April 2017 issue of Visual Studio Magazine that explains R language OOP using the so-called S4 model. See https://visualstudiomagazine.com/articles/2017/04/01/r-s4-demo.aspx.
OOP in the R language is very different from OOP in general purpose languages such as Java, C#, and Python. First of all, there are three entirely different ways to write R language OOP — S3, S4, and RC. In my article I give a summary of S4 in this way:
To summarize, you define an S4 class using the setClass function. The “slots” keyword (replaces the deprecated “representation”) defines field names and their types. You can optionally define a validity-check function, or implement a primitive form of inheritance using the “contains” keyword. All fields have public scope and are accessed using the “@” operator. You use setMethod to define an “initialize” function (replaces the deprecated “prototype”) with an “.Object” parameter that sets initial field values. You use a pair of setGeneric and setMethod to define a class method.
Calling an S4 object is somewhat more similar to other programming languages. In my article I define a Person class and call it like this:
cat("\nBegin OOP with S4 demo ") cat("Creating Person p1 with initialize values ") p1 <- new("Person") # could use p1 <- Person display(p1) # could use print(p1) cat("Setting p1 fields directly ") p1@empID <- as.integer(65565) p1@lastName <- "Adams" p1@hireDate <- "2010-09-15" p1@payRate <- 43.21 display(p1) cat("Calling yearsService ") tenure <- yearsService(p1) cat("Person p1 tenure = ", tenure, " years ") cat("Making a value-copy of p1 using '<-' ") p2 <- p1 cat("\nEnd OOP with S4 demo ")
I don’t write S4 OOP code very often, but when I do, I pull out the demo code I created for this article to remind myself of S4 syntax.