How can one call the superclass method from a subclass method and return control to the subclass method for an S4 class?

Viewed 30

If I make two classes like such:

setClass("SuperClass", slots=c(a="character"), prototype=list(a="A"))
setClass("SubClass", slots=c(b="character"), prototype=list(b="B"), contains="SuperClass")

and some method like such:

setGeneric("foobar", function(x) standardGeneric("foobar"))
setMethod("foobar", "SuperClass", function(x) { cat(x@a, "\n", sep="") })

How can I write a method foobar for the class SubClass that can call the foobar method for SuperClass and then do some other SubClass specific computation?

The method could look something like this:

setMethod("foobar", "SubClass", function(x) {
        # call SuperClass's foobar
        cat(x@b, "\n", sep="")
})

and then if I do this:

x <- new("SubClass")
foobar(x)

it should print

"A"
"B"

Of course this is a trivial use-case that can be solved by other approaches, but I think it captures that spirit of what I am trying to do.

1 Answers

You need callNextMethod:

setMethod("foobar", "SubClass", function(x) {
        callNextMethod()
        cat(x@b, "\n", sep="")
})
x <- new("SubClass")
foobar(x)
# A
# B
Related