As noted, an advantage of using S4 is safety. To illustrate this, suppose
we were to accidentally spellsalaryassalry, like this:
joe@salry <- 48000
Error in checkSlotAssignment(object, name, value) :
"salry" is not a slot in class "employee"
By contrast, in S3 there would be no error message. S3 classes are just
lists, and you are allowed to add a new component (deliberately or not) at
any time.
9.2.2 Implementing a Generic Function on an S4 Class..................
To define an implementation of a generic function on an S4 class, use
setMethod(). Let’s do that for our class"employee"here. We’ll implement
theshow()function, which is the S4 analog of S3’s generic"print".
As you know, in R, when you type the name of a variable while in inter-
active mode, the value of the variable is printed out:
joe
An object of class "employee"
Slot "name":
[1] "Joe"
Slot "salary":
[1] 88000
Slot "union":
[1] TRUE
Sincejoeis an S4 object, the action here is thatshow()is called. In fact,
we would get the same output by typing this:
show(joe)
Let’s override that, with the following code:
setMethod("show", "employee",
function(object) {
inorout <- ifelse(object@union,"is","is not")
cat(object@name,"has a salary of",object@salary,
"and",inorout, "in the union", "\n")
}
)
The first argument gives the name of the generic function for which we
will define a class-specific method, and the second argument gives the class
name. We then define the new function.
Object-Oriented Programming 225