Object Oriented Programming (OOP) is all too often viewed by those unfamiliar to it as a science to be mastered. OOP however, is an art...a methodology, a simple (but powerful) way of defining what a program is. After going through many tutorials on the subject some of us still scratched our heads and lamented, "Interesting philosophy, but I still don't know how to do OOP." We wanted to master a science and we couldn't find the telltale step-by-step instructions we were looking for. So, I've written this article to save you that frustration.
Placing objects inside a program does not, by itself, make it Object Oriented. For that to happen we need to consider how the parts of a program relate to each other. Let's think of a pet tracking program as just a bunch of instructions thrown together...now OOP sees that same program rearranged as several self-contained groups of related functions and variables (these groupings are determined by your common-sense). Don't make this more complicated..that's THE concept!
These groups are called Classes (which is just a blueprint for an object). For example, a dog class may have a "doTrick" subroutine and a "breed" variable, but no "sweater-size" (that's absolutely ridiculous, but I digress). Dog tricks and breeds are both related to 'dog', that's the common-sense part. 'Class' is a blueprint, just as 'integer' is an existing blueprint when you declare "i" as 'integer.' And with OOP, a variable like "i" can be declared from a 'dog' blueprint. The difference here is that you, the programmer, write the code that defines 'dog'. After making that dog-blueprint you can declare a new variable (like "i") as an instance of 'dog.' That can then be filled with unique data and passed around to other objects in the program.
Rules must be used to govern what parts of an object are seen (and/or altered) by other objects in the program (aka “Encapsulation"). So let's make a rule. Well, 'color' is seen by people (who, incidentally, would probably be a class). They are allowed to get your dog's color but shouldn't be allowed to set it. "Purple poodle" I hear you say? Well, if you insist. But to do that, let's declare a new 'fancy dog' class (one with sweater-size and settable color). Here OOP gives us something wonderful..we can reuse ALL the existing class code in 'dog' (and no, it's not cut and paste)! In OOP we just create an empty class named 'fancy_dog', and tell it to inherit from the existing 'dog' class. We then just add sweater-size and color as new variables inside it (remembering to make color settable) ….and now we're doing serious OOP!
**If you found this article helpful, please click the "Thumbs-Up" (below and to the left).
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.