Sarang Manjrekar
Sarang Manjrekar

Reputation: 1991

How to make an S4 class inherit correctly from another S4 class?

I am creating two S4 classes, where class Employee inherits from the other class Person.

The definition for both the classes is as follows:

setClass("Person", slots = list(name="character", age="numeric"))

setClass("Employee", slots = list(boss="Person"))

I am creating once instance each of these two classes,

alice <- new("Person", name="Alice", age = 40)

This works well, but when I try to create an instance of Employee using :

john <- new("Employee", name = "John", age = 20, boss= alice)

It gives the error as below :

Error in initialize(value, ...) : 
  invalid names for slots of class “Employee”: name, age

Can I not create the object in this fashion ?

Upvotes: 3

Views: 854

Answers (1)

Joris Meys
Joris Meys

Reputation: 108543

Per nrussel's comment:

the argument contains of the function setClass deals with inheritance. You want the class Employee to inherit from the class Person (i.e. an employee is a special type of person). So

setClass("Person", slots = list(name="character", age="numeric"))
setClass("Employee", slots = list(boss="Person"), contains = "Person")

will do the trick.

> alice <- new("Person", name="Alice", age = 40)
> john <- new("Employee", name = "John", age = 20, boss= alice)
> john
An object of class "Employee"
Slot "boss":
An object of class "Person"
Slot "name":
[1] "Alice"

Slot "age":
[1] 40


Slot "name":
[1] "John"

Slot "age":
[1] 20

Upvotes: 5

Related Questions