Inheritance in Java

An explanation of inheritance in Java using Karel J. Robot.

 

Inheritance is an important concept in programming because it allows software re-use.  This in important because it saves time, space, effort, and reduces the workload on the computer.  In Karel J. Robot, inheritance was used going from the UrRobot class to the Robot class to the SuperRobot class.  Each time more methods were added, and we didn’t quite know how or why until now.

The parent class for all of this was the UrRobot class.   This class only had a constructor and the methods for moving, turning left, and picking up and placing beepers.  This was a very simple class and didn’t allow the user to do very much without making a very detailed driver class.

The second class and child of the UrRobot class was the Robot class.  This class inherited all the methods from the UrRobot class, allowing it to move around, turn left, and pick and put beepers.  The class took the basics of the “robot”, and added on many Boolean methods, allowing the user to use if/else and while/for loops in the driver class, making many repetitive actions easier and allowing the robot to make decisions for itself during the execution of the driver class.

The final class in the hierarchy, the SuperRobot class, was the child of the Robot class.  This means it inherited all the basic methods for moving and dealing with beepers from the UrRobot class, as well as the Boolean methods from the Robot class.  The SuperRobot class also had its own constructor, which overrode the constructor from the UrRobot class because it was a child class and therefore more specific than the parent.  When we finally got to the SuperRobot class, we learned more about creating our own methods.  With the basic foundations needed to make the methods inherited from Robot and UrRobot, we were able to write our own methods.

This example of an inheritance hierarchy shows how methods can be passed from parent to child and continuously down to other children.  Because of inheritance, we were able to save a lot of time because we did not have to re-write all of the methods from UrRobot and Robot when we made SuperRobot. 

Leave Your Response