Требования к методам

Интерфейсы

# A virtual class has no objects of its own
setClass("Car", representation("VIRTUAL"))

# Methods every car must have
setGeneric("start_engine", function(car) {
  standardGeneric("start_engine")
})
# [1] "start_engine"
setGeneric("stop_engine", function(car) {
  standardGeneric("stop_engine")
})
# [1] "stop_engine"

setClass("SportCar", contains = "Car")

setMethod("start_engine", "SportCar",
          function(car) {
            cat("start engine\n")
            TRUE
          })
setMethod("stop_engine", "SportCar",
          function(car) {
            cat("stop engine\n")
          })

car <- new("SportCar")
started <- start_engine(car)
# prints "start engine"
stop_engine(car)
# prints "stop engine"

cat("started =", started, "\n")

# A method is missing: the object is created,
# and the call fails
setClass("NoStopCar", contains = "Car")
no_stop <- new("NoStopCar")
call_error <- tryCatch(stop_engine(no_stop),
                       error = conditionMessage)
cat("call_error =", call_error, "\n")
# call_error = unable to find an inherited
# method for function ‘stop_engine’ for
# signature ‘car = "NoStopCar"’