Classes…Extended Version


The main focus of programming in a object oriented style is to reuse as much code as humanly possible.  In other words, you do not want to write the same code more than one time.  Why?  Well first off, it is inefficient and wastes your valuable time.  More importantly though, you don’t want to have to make changes later on in more than one place and try to remember all the different places that the code needs to be updated.

Extending a class goes right to the heart of this concept.  It allows to you have different classes that all share some common elements.  Going back to our bicycle example, let’s assume that a bike app works for road bikes and BMX bikes.  Each one has a frame, handlebars, a chain, etc., but the road bike has elements that the BMX bike does not have, such as gears.

So a class for the BMX bike doesn’t need a function for selecting a gear, but a class for a road bike does.  Our standard bicycle class works fine for the BMX bike, so no worries there.  Rather than add an unneeded function to our standard bicycle class, or copying the standard class to a new class and adding the function, we can simply extend the standard class.  An extended class inherits (or more simply, can access) the properties and methods of the “parent” class.  Parent is just a fancy term for the class being extended.

While the parent functions like pedal() are accessible to the RoadBike class, the reverse is not true.  An instance of the Bicycle class cannot access functions in the RoadBike class. The only nuances to extending classes are that the extended class can see public and protected properties & methods, but not ones that are declared as private.  This is called inheritance.

Inheritance and visibility are a whole different subject that I will cover next time around. Until then, have fun and happy coding!

-Andy

, ,

Comments are closed.