Inheritance
í
In object-oriented (OO) programming, reusability of code plays a big role. Think of OO programmers as like they were smart sloths. They don't want to do much in general, and so they don't want to re-do many things. That's why the concept of objects was invented. Now, if you have a, let's say, class that provides certain functionality, you might want to provide this class with some extra functionality that someone (or even you) has done already.
The most common ways to do so are the concepts of Inheritance and composition. In the following, I will give an example of how to use them.
And this is the ouput:
The Child class inherits from the Parent class, which means that it gets some extra functionality. There are basically three things happening here:
overriding means that you can give a certain inherited method other functionality than the one from the parent class. This works by just defining the method in the child class with the same name as in the parent class.
alter means that you can add functionality of methods of the parent class using super(). You have to name the altered method exactly like in the parent class. You can then do whatever you want inside this method (as in overriding), but you can call the original method anytime within the altered method. For this, a simple super() calls the original method.
The most common ways to do so are the concepts of Inheritance and composition. In the following, I will give an example of how to use them.
- class Parent
- def override()
- puts "PARENT override"
- end
- def implicit()
- puts "PARENT implicit call"
- end
- def altered()
- puts "PARENT altered"
- end
- end
- class Child < Parent
- def override()
- puts "CHILD override"
- end
- def altered()
- puts "CHILD, BEFORE PARENT altered"
- super()
- puts "CHILD, AFTER PARENT altered"
- end
- end
- parent = Parent.new()
- child = Child.new()
- parent.implicit()
- child.implicit()
- parent.override()
- child.override()
- parent.altered()
- child.altered()
And this is the ouput:
- PARENT implicit call
- PARENT implicit call
- PARENT override
- CHILD override
- PARENT altered
- CHILD, BEFORE PARENT altered
- PARENT altered
- CHILD, AFTER PARENT altered
- implicit inheritance
- overriding an inherited method
- alter an inherited method
overriding means that you can give a certain inherited method other functionality than the one from the parent class. This works by just defining the method in the child class with the same name as in the parent class.
alter means that you can add functionality of methods of the parent class using super(). You have to name the altered method exactly like in the parent class. You can then do whatever you want inside this method (as in overriding), but you can call the original method anytime within the altered method. For this, a simple super() calls the original method.