R Inheritance - r - learn r - r programming
- One the most useful feature of an object oriented programming language is inheritance.
- Defining new classes out of existing ones.
- This is to say, we can derive new classes from existing base classes and adding new features.
- We don't have to write from scratch.
- Hence, inheritance provides reusability of code.
- Inheritance forms a hierarchy of class just like a family tree.
- Important thing to note is that the attributes define for a base class will automatically be present in the derived class.
- Moreover, the methods for the base class will work for the derived.
r programming inheritance
- Below, we discuss how inheritance is carried out for the three different class systems in R programming language.
Inheritance in S3 Class
- S3 classes do not have any fixed definition.
- Hence attributes of S3 objects can be arbitrary.
- Derived class, however, inherit the methods defined for base class.
- Let us suppose we have a function that creates new objects of class student as follows.
- Furthermore, we have a method defined for generic function print() as follows.
- Now we want to create an object of class InternationalStudent which inherits from student.
- This is be done by assigning a character vector of class names like class(obj) <- c(child, parent).
Sample Code
Output:
- We can see above that, since we haven't 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().
- This will overwrite the method defined for class student as shown below.
- We can check for inheritance with functions like inherits() or is().
Inheritance in S4 Class
- Since S4 classes have proper definition, derived classes will inherit both attributes and methods of the parent class.
- Let us define a class student with a method for the generic function show().
- Inheritance is done during the derived class definition with the argument contains as shown below.
- Here we have added an attribute country, rest will be inherited from the parent.
- We see that method define for class student got called when we did show(s).
- We can define methods for the derived class which will overwrite methods of the base class, like in the case of S3 systems.
Inheritance in Reference Class
- Inheritance in reference class is very much similar to that of the S4 class.
- We define in the contains argument, from which base class to derive from.
- Here is an example of student reference class with two methods inc_age() and dec_age().
- Now we will inherit from this class. We also overwrite dec_age() method to add an integrity check to make sure age is never negative.
- Let us put it to test.
- In this way, we are able to inherit from the parent class.