R – Inheritance

Inheritance and Their Types

Inheritance is one of the key concepts in object-oriented programming, enabling new classes to be derived from existing or base classes, thereby enhancing code reusability. Derived classes can inherit properties and behaviors from the base class or include additional features, creating a hierarchical structure in the programming environment. This article explores how inheritance is implemented in R programming using three types of classes: S3, S4, and Reference Classes.

Inheritance in S3 Class

S3 classes in R are informal and have no rigid definitions. They use lists with a class attribute set to a class name. Objects of S3 classes inherit only methods from their base class.

Example:

# Create a function to define a class
employee <- function(n, a, e){
  obj <- list(name = n, age = a, emp_id = e)
  attr(obj, "class") <- "employee"
  obj
}

# Define a method for the generic function print()
print.employee <- function(obj){
  cat("Name:", obj$name, "\n")
  cat("Age:", obj$age, "\n")
  cat("Employee ID:", obj$emp_id, "\n")
}

# Create an object and inherit the class
e <- list(name = "Priya", age = 30, emp_id = 123,
          department = "HR")
class(e) <- c("Manager", "employee")

cat("Using the inherited method print.employee():\n")
print(e)

# Overwrite the print method
print.Manager <- function(obj){
  cat(obj$name, "is a Manager in", obj$department, "department.\n")
}

cat("After overwriting the method print.employee():\n")
print(e)

# Check inheritance
cat("Is the object 'e' inherited from class 'employee'?\n")
inherits(e, "employee")

Output:

Using the inherited method print.employee():
Name: Priya
Age: 30
Employee ID: 123
After overwriting the method print.employee():
Priya is a Manager in HR department.
Is the object 'e' inherited from class 'employee'?
[1] TRUE
Inheritance in S4 Class

S4 classes in R are more formal, with strict definitions for slots. Derived classes can inherit both attributes and methods from the base class.

Example:

# Define an S4 class
setClass("employee",
         slots = list(name = "character",
                      age = "numeric", emp_id = "numeric")
)

# Define a method to display object details
setMethod("show", "employee",
          function(obj){
            cat("Name:", obj@name, "\n")
            cat("Age:", obj@age, "\n")
            cat("Employee ID:", obj@emp_id, "\n")
          }
)

# Create a derived class
setClass("Manager",
         slots = list(department = "character"),
         contains = "employee"
)

# Create an object of the derived class
m <- new("Manager", name = "Priya", age = 30, emp_id = 123, department = "HR")
show(m)

Output:

Name: Priya
Age: 30
Employee ID: 123
Inheritance in Reference Class

Reference classes use the setRefClass() function to create classes and manage inheritance. The concept is similar to S4 classes but supports mutable objects.

Example:

# Define a reference class
employee <- setRefClass("employee",
                        fields = list(name = "character",
                                      age = "numeric", emp_id = "numeric"),
                        methods = list(
                          increment_age = function(x) {
                            age <<- age + x
                          },
                          decrement_age = function(x) {
                            age <<- age - x
                          }
                        )
)

# Create a derived reference class
Manager <- setRefClass("Manager",
                       fields = list(department = "character"),
                       contains = "employee",
                       methods = list(
                         decrement_age = function(x) {
                           if ((age - x) < 0) stop("Age cannot be negative")
                           age <<- age - x
                         }
                       )
)

# Create an object
mgr <- Manager(name = "Priya", age = 30, emp_id = 123, department = "HR")

cat("Decreasing age by 5:\n")
mgr$decrement_age(5)
mgr$age

cat("Attempting to decrease age by 30:\n")
mgr$decrement_age(30)
mgr$age

Output:

Decreasing age by 5:
[1] 25
Attempting to decrease age by 30:
Error in mgr$decrement_age(30) : Age cannot be negative
[1] 25

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *