Ruby is the ideal object-oriented language. In an object-oriented programming language, inheritance is one of the most important features. Inheritance allows the programmer to inherit the characteristics of one class into another class. Ruby supports only single class inheritance, it does not support multiple class inheritance but it supports mixins. The mixins are designed to implement multiple inheritances in Ruby, but it only inherits the interface part.
Inheritance provides the concept of “reusability”, i.e. If a programmer wants to create a new class and there is a class that already includes some of the code that programmer wants, then he or she can derive a new class from the existing class. By doing this, it increases the reuse of the fields and methods of the existing class without creating extra code.
In the above image class A is super class and class B is a subclass or you can say class B is derived from class A(Base Class).
Key terms in Inheritance:
- Super class:The class whose characteristics are inherited is known as a superclass or base class or parent class.
- Sub class:The class which is derived from another class is known as a subclass or derived class or child class. You can also add its own objects, methods in addition to base class methods and objects etc.
Note: By default, every class in Ruby has a parent class. Before Ruby 1.9, Object class was the parent class of all the other classes or you can say it was the root of the class hierarchy. But from Ruby 1.9 version, BasicObject class is the super class(Parent class) of all other classes in Ruby. Object class is a child class of BasicObject class.
subclass_name < superclass_name
This is Superclass This is Subclass Method of superclass
Overrriding of Parent or Superclass method: Method overriding is a very effective feature of Ruby. In method overriding, subclass and superclass contain the same method’s name, but performing different tasks or we can say that one method overrides another method. If superclass contains a method and subclass also contain same method name then subclass method will get executed.
Override by Subclass
Use of super Method in Inheritance: This method is used to call the parent class method in child class. If the method does not contain any argument it automatically passes all its argument. A super method is defined by super keyword. Whenever you want to call parent class method of the same name so you can simply write super or super().
Parent class, 1st Argument: Sudo_Placement, 2nd Argument: GFG Parent class, 1st Argument: Sudo_Placement, 2nd Argument: 0 Parent class, 1st Argument: Sudo_Placement, 2nd Argument: GFG Parent class, 1st Argument: 0, 2nd Argument: 0 Hey! This is subclass method
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.