Open In App

R - Inheritance

Last Updated : 12 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Inheritance is one of the concept in object oriented programming by which new classes can derived from existing or base classes helping in re-usability of code. Derived classes can be the same as a base class or can have extended features which creates a hierarchical structure of classes in the programming environment. In this article, we'll discuss how inheritance is followed out with three different types of classes in R programming.

Inheritance in S3 Class

S3 class in R programming language has no formal and fixed definition. In an S3 object, a list with its class attribute is set to a class name. S3 class objects inherit only methods from its base class.

1. Creating the student class constructor

The first part of the code defines a function student that takes three arguments: name, age and roll number. Inside the function, we create a list value that holds these three attributes. Afterward, we assign the class student to this list by using the attr() function. This makes the list an object of the student class and we return the object to be used later.

R
student <- function(n, a, r) {
  value <- list(name = n, age = a, rno = r)
  attr(value, "class") <- student
  value
}

2. Defining the print.student method

Next, we define a method called print.student. This method is specifically designed to handle objects of the student class. When we call print() on a student object, this method will be executed. The print.student method uses the cat() function to display the student's name, age and roll number on the screen.

R
print.student <- function(obj) {
  cat(obj$name, "\n")
  cat(obj$age, "\n")
  cat(obj$rno, "\n")
}

3. Creating a basic student object

We then create a student object s by making a list with the student's name, age, roll number and country. After creating this list, we assign two classes to it: "InternationalStudent" and "student". The order of these classes matters because R will try to find the method in the first class and then fall back to the second if it doesn't find it. This is done by setting the class() attribute for the object.

R
s <- list(name = "Utkarsh", age = 21, rno = 96, country = "India")
class(s) <- c("InternationalStudent", "student")

4. Calling the print method on the student object

After defining the object s, we call print(s) to print its details. Since the print.student method is defined, it gets called. This method prints the name, age and roll number of the student as specified in the earlier code block.

R
cat("The method print.student() is inherited:\n")
print(s)

Output:

The method print.student() is inherited:
Utkarsh
21
96

5. Overriding the print method for InternationalStudent

At this point, we define a new print method specifically for objects of the class "InternationalStudent". This method will print the student's name and their country, instead of just the name, age and roll number. This effectively overrides the previous print behavior when the object has the InternationalStudent class.

R
print.InternationalStudent <- function(obj) {
  cat(obj$name, "is from", obj$country, "\n")
}

6. Calling the overridden print method

After defining the new print method for "InternationalStudent", we call print(s) again. This time, the overridden print.InternationalStudent method gets invoked because the object s now also belongs to the InternationalStudent class. This method prints the student's name along with the country they are from, which shows the behavior of inheritance and method overriding in action.

R
cat("After overwriting method print.student():\n")
print(s)

Output:

After overwriting method print.student():
Utkarsh is from India

7. Checking if object s inherits from the student class:

Finally, we use the inherits() function to check if the object s is inherited from the student class. This function returns TRUE because the object s is indeed of class student (since student is part of the class hierarchy of s).

R
cat("Does object 's' inherit from class 'student'? ", inherits(s, "student"), "\n")

Output:

Does object 's' inherit from class 'student'? TRUE

Inheritance in S4 Class

S4 class in R programming have proper definition and derived classes will be able to inherit both attributes and methods from its base class.

1. Defining the S4 class student

The first part of the code defines an S4 class named student with three slots: name, age and rno (roll number). S4 classes allow you to specify types for each slot, ensuring that only valid data is stored in the object.

R
setClass("student",
         slots = list(name = "character", 
                      age = "numeric", rno = "numeric") 
)

2. Defining a method to display object details

Next, we define a show method for the student class. This method will print the name, age and rno of the object when it is printed using the show() function. The @ operator is used to access the slots of an S4 object.

R
setMethod("show", "student",
          function(obj){
            cat(obj@name, "\n")
            cat(obj@age, "\n")
            cat(obj@rno, "\n")
          } 
)

3. Inheriting from student class to create InternationalStudent

In this section, we create a new class InternationalStudent, which inherits from the student class. This means that InternationalStudent objects will have all the slots of the student class (i.e., name, age and rno). We add an extra slot country to store the country of the international student.

R
setClass("InternationalStudent",
         slots = list(country = "character"),
         contains = "student"
)

4. Creating an object of InternationalStudent and displaying details

Here, we create an object s of the class InternationalStudent using the new() function. We pass values for name, age, rno and country. Then, we call the show(s) method to print the details of the s object, which includes information from both the inherited student class and the country attribute from InternationalStudent.

R
s <- new("InternationalStudent", name = "Utkarsh", 
         age = 21, rno = 96, country="India")
show(s)

Output:

Utkarsh
21
96

Inheritance in Reference Class

Inheritance in reference class is almost similar to the S4 class and uses setRefClass() function to perform inheritance.

1. Defining the student class using setRefClass

The first part of the code defines a student class using setRefClass, which allows us to create reference classes in R. We define three fields: name, age and rno. We also define two methods: inc_age (to increase the age) and dec_age (to decrease the age). These methods modify the age field of the object.

R
student <- setRefClass("student",
   fields = list(name = "character",
                 age = "numeric", rno = "numeric"),
   methods = list(
     inc_age = function(x) {
       age <<- age + x
     },
     dec_age = function(x) {
       age <<- age - x
     }
   )
)

2. Inheriting from the student class to create InternStudent

In this step, we create a new class InternStudent that inherits from the student class using the contains argument. In addition to the fields inherited from student, we define an extra field country and override the dec_age method. The overridden dec_age method ensures that the age doesn't go below zero by checking if the age minus the decrement is negative. If so, it stops the operation with an error message.

R
InternStudent <- setRefClass("InternStudent", 
   fields = list(country = "character"), 
   contains = "student",
   methods = list(
     dec_age = function(x) {
       if ((age - x) < 0) {
         stop("Age cannot be negative")
       }
       age <<- age - x
     }
   ) 
)

3. Creating an InternStudent object and modifying the age

Here, we create an object s of the InternStudent class by passing values for name, age, rno and country. Then, we call the dec_age method twice: first to decrease the age by 5 and then by 20. The first call is successful, but the second call will result in an error because it will attempt to reduce the age below zero.

R
s <- InternStudent(name = "Utkarsh",
                   age = 21, rno = 96, country = "India")

cat("Decrease age by 5\n")
s$dec_age(5)
cat("Age after decreasing by 5:", s$age, "\n")

Output:

Decrease age by 5
Age after decreasing by 5: 16

In this article, we discussed how inheritance was followed out with three different types of classes in R programming.


Next Article
Practice Tags :

Similar Reads