-->

Thursday, August 22, 2013

Code Concepts: Object Oriented Programming (Overview)

When you start out programming in a language like Java or C++, one of the first basics that is oft repeated is object oriented programming.

What is object oriented programming precisely?

Prior to OOP, procedural languages were the way to go. Languages such as BASIC, FORTRAN and the like. The issue with these languages were that they required one to rewrite and repeat code continually.

As such, OOP was developed, which gave substantial versatility and ease of use to the principles of programming.  It all boils down to three key concepts, which will be covered in more detail with time.

1) Encapsulation - This is when you protect your code to keep it from being utilized incorrectly. Hiding it so that its easy to use and change, yet doesn't influence (or is influenced by) the entire system.  Afterall, if a Ferrai isn't working due to a bad headlight, you replace the headlight, not the entire car.

2) Inheritance - When the behavior of one "super" or "parent" class is extended to a "child" subclass. What behavior is at the top falls to all children below it. This can be convenient, though care must be taken to properly define common features of classes.

A good test for inheritance is the Is-A test. Take being humans and its relationship to Animals.



Every Dog is an Animal. True
Every Animal is a Dog. False.


A salesman is a job.
A job is a salesman.


In this case, inheritance would apply.
3) Polymorphism - When a subclass is composed of its inheritors in a manner that allows a it to stand in for the superclass. This allows varied behaviors at runtime. In Java, this is achieved through interfaces and overloading (for methods and constructors).

Allows subclass to stand in for a superclass.

To test for such, HAS-A statements help clarify such relationships.


A human has a gender. True
A gender has a human. False


A human has a ethnicity.
An ethnicity has a human.


A human has a job.
A job has a human.


A human has a hobby.
A hobby has a human.

A human has clothes.

A clothes has human.


In this case, polymorphism can applies. Also known as aggregation or  composition. As we all know, human beings are complex creatures with their own separate qualities and interests.


Aggregate enough these various behaviors together however, and you can begin to narrow down to specific individuals.


Human1 has a gender of "male."
Human1 has a job of "president."
Human1 has an ethnicity of "black."
Human1 has a hobby of "golf."
Human1 has a clothing style of "business."


Human2 has a gender of "female."
Human1 has a job of "president."
Human1 has an ethnicity of "black."
Human1 has a hobby of "golf."
Human1 has a clothing style of "business."



~David Morris~

No comments:

Post a Comment