This post talks about how to implement basic inheritance in Ruby using a simple example. I’ll throw in some comparisons with Java.
Our Parent and Child Classes
The simplest example of Parent-child inheritance is as follows.
1 2 3 4 5 6 7 | class Parent # methods and other codes here end class Child < Parent # methods and other codes here end |
In Java, this is equivalent to
1 2 | public class Parent {} public class Child extends Parent {} |
Overriding methods
Let’s modify the original Ruby codes so that the Parent class has a method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class Parent def walk puts "In parent..." end end class Child < Parent # No methods defined or re-defined here end # Let’s create an instance of Child # and invoke the inherited walk method my_child = Child.new my_child.walk() |
These codes will output:
1 | In parent... |
Now if we re-define the same walk method in the Child class that displays a different string
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | class Parent def walk puts "In parent..." end end class Child < Parent def walk puts "In Child..." end end # Let’s create an instance of Child # and invoke the inherited walk method my_child = Child.new my_child.walk() |
These codes will output:
1 | In Child... |
That’s it! That’s pretty much it though there are other concepts around Ruby inheritance.