Declaration and initialization

Interfaces

# An interface: a virtual class
setClass("Printable", representation("VIRTUAL"))
# Its method: a generic without a body
setGeneric("print_in_color", function(x, color) {
  standardGeneric("print_in_color")
})
# [1] "print_in_color"

# A class that implements the method
setClass("Document", contains = "Printable")
setMethod("print_in_color", "Document",
          function(x, color) {
            cat("printing in", color, "\n")
          })

printable <- new("Document")
print_in_color(printable, "red")
# prints "printing in red"

# The interface itself cannot be created
msg <- tryCatch(new("Printable"),
                error = conditionMessage)
cat("msg =", msg, "\n")
# msg = trying to generate an object from
# a virtual class ("Printable")