R Inheritance

One the main concept of object oriented programming is inheritance which allows us to define a new class of existing classes. This means that we can derive new classes from existing base classes and adding new features. Hence, inheritance provides re-usability of code.

Inheritance in S3 class

Since S3 classes do not have any fixed definition. Hence attributes of S3 objects can be arbitrary. As we know, derived class inherits the methods defined for base class.

For example, we have a function that creates new objects of class student as follows:

And we have a method defined for generic function print() as follows:

Now, we want to create an object of the class InternationalStudent which inherits from student.

This is be done by assigning a character vector of class names like class(obj) <- c(child, parent).

Example:

Output:

From the above example we can see that, since we have not defined any method of the form print.InternationalStudent(), the method print.student() got called. This method of class student was inherited.

Now, let us define print.InternationalStudent():

Output:

Inheritance in S4 Class

Since S4 classes have proper definition, derived classes will inherit both attributes and methods of the parent class.

Let’s define a class student with a method for the generic function show():

Inheritance is done during the derived class definition with the argument contains:

Here, new attribute is country; rest will be inherited from the parent.

Output:

Inheritance in Reference Class

It is similar to S4 class.

Example:

Let’s see an example of student reference class with two methods inc_age() and dec_age().

Now we will inherit from this class. We also overwrite a method dec_age() to add an integrity check to make sure age is never negative.

Let’s test it:

Output: