What is Object Oriented Programming

YouTube Preview ImageWelcome to a brief tutorial on what is Object Oriented Programming (OOP) and why the object oriented approach is considered the best way to program. Objects programming has taken the world by storm because of its flexibility and understandability, but learning the concepts behind it are sometimes a bit daunting. I will do my best to explain it in the simplest of terms. I assume you have a minor understanding of programming in this article, but if not, you can read my Javascript Scripting Tutorial to get prepared.

What Are Objects in Object Oriented Programming

A while back when a programmer sat down to write a program he/she would first ask “What does this program have to do?” They would then create a program that was filled with one action after another. This is known as procedural programming.

Now most programmers instead ask themselves, “What things are in this program?” Then they write code that explains what functions these things (objects) should be able to do. This is known as Object Oriented Programming (OOP).

Let’s say you are told to create a program that copies the functionality of a car. Here is a basic example of how you might do that with procedural programming versus OOP.

Procedural Version

driveForward (carType) {
// Code
}

stopCar (CarType) {
// Code
}

honkHorn (carType) {
// Code
}

OOP Version

Car

driveForward (carType) {
// Code
}

stopCar (CarType) {
// Code
}

honkHorn (carType) {
// Code
}

Not much difference here. With the procedural code you define all of the functions that the car needs to perform. While in the OOP code you define a Car Object and then list all of the functions it needs to perform. What do you do if you have to assign a different car horn for multiple different vehicles?

Procedural Version

driveForward (carType) {
// Code
}

stopCar (CarType) {
// Code
}

honkHorn (carType) {
if (carType = “carA”)
else if (carType = “carB”)
….
// Code
}

OOP Version

carA of type Car

honkHorn (carType) {
// Code
}

carB of type Car

honkHorn (carType) {
// Code
}

Ok, Mr. Procedural had to add a bunch of “if” statements that would play a different car honk, based off of which car is honking. Mrs. OOP, just created a new object that kept using all of the functions related to the car Object, except where it over-wrote the function honkHorn.

Now your told that some cars will drive forward in the same way, but you have to create a new driveForward function for all-terrain vehicles. Mr. Procedural adds a bunch of “if” statements to the driveForward function. Mrs. OOP doesn’t need to touch the working code, but like before just types in a new function that gives the all-terrain capabilities.

As you can see OOP code is a lot neater and organized, because if you want to add on a new capability you just create a new function without touching any of the old code.

Inheritance

One of the reasons Object Oriented Programming requires less code to get things done is because of a concept called Inheritance. In the example above you first created a basic Car Object. Then the objects carA and carB where able to inherit all of the capabilities that all cars have while overiding those features that differ. The car object above is what we would refer to as the superclass.

Classes

You may have caught me using the word superclass? “I thought we were talking about objects, what is a class”, you may ask? A class is a blue print that describes how to build many classes. Let’s create a class below:

class car {
var engine;
var gasTank;
var door;

driveForward();
driveBackward();
stop();
openDoor();
getGas();
}

Now with this class you can create as many objects and sub-objects as you like. Each one will have all of the above variables (called instance variables in OOP) and functions (called methods in OOP). And, remember each object has the ability to easily override those functions it can’t use. Most programming langauges create an object with the following statement:

className objectToCreate = new className();

or for example:

car dodge = new car();

On a side note it is considered good practice to include functions (methods), in the class definition, that are the sole way to access the variables in the object.

Accessing the Methods and Instance Variables

So how do you access a method or variable that lies in a newly created object? You use the dot (.) operator. Remember I said that it is good practice to create functions that edit or pass object variables, as well. Here is an example:

class car {
var engine;
var gasTank;
var door;

driveForward(var howFar)
driveBackward();
stop();
openDoor();

getGas();
getGasTank() { // Defining what the method in this object will do. It returns the value of the gasTank variable.
return gasTank;
}

setGasTank();
}

car dodge = new car(); // Creates a new object of type car, named dodge
fuelInTank = dodge.getGasTank(); // Would return the amount of fuel in the gas tank

I’ve been holding out on you. By only accessing your variables through the use of methods, you have been given the honor to say you know how to Encapsulate. Encapsulating your code you are protecting it from getting accidentally edited. You do this by creating two methods for each variable you define. One of those methods returns the value (It is best to start this method with the word get) of a variable and the other changes the value of that variable (It is best to start this method with the word set).

Depending on what OOP language you are using there may or may not be ways to enforce encapsulation? So I won’t get into public and private in this article. I also will skip over the concepts of primitives and references for the same reason. If you want me to write an article on OOP in a specific language  I’d be happy to.

Polymorphism: Whoo! Your Going to Learn What this Big Word Means

Let us take a step back to make sure you understand inheritance. Remember when we defined the original car class above? Then we created a subclass of the superclass car and named it dodge? In OOP that is known as extending the superclass. So, dodge inherited all of the functionality of class car and then extended it with a new method named honkHorn().

You could have also created new variables and methods for the dodge class, without changing the superclass in anyway.  Also remember that (dodge object) is always a (car object), but a (car object) is not a (dodge).To use another example all monkeys are animals, but all animals aren’t monkeys.

By using Inheritance you will:

  • Decrease duplicate code
  • Decrease searching time for what code needs to be changed
  • Avoid breaking previously working code
  • Simplify your code overall

On to the Polymorphism All Ready

When you type the following: carA dodge = new  carA(); You are telling the computer to do the following:

  • carA dodge : Tells the computer a variable of type carA named dodge is being created.
  • new carA() : Set aside space in memory for a new carA object.
  • Then the equals sign assigns the carA object to the variable named dodge.
  • The dodge variable and the carA object both are the same. dodge is just a variable name that points to the carA object in memory.

You may be saying “But, there are thousands of types of cars, isn’t that going to make everything confusing?” Without polymorphism you would have such confusing definitions as car.toyota.truck.4×4…

With Polymorphism you can simply define a new object using the superclass like this:

car dodge = new carA(); // Declaring a object dodge to be of the superclasses type

What does that allow you to do? You can now create one function that automatically works with all subclasses of class car. Here is an example:

class Car {
tuneUp ( CAR a) {
a.driveForward(); // Will run these functions no matter what subclass was passed
a.driveBackward();
a.stop();
}
}

I think you can see how Polymorphism can save you a ton of time.

Note: Here is another way to think about Polymorphism, if you still don’t get it!

Polymorphism provides you with a way to write code that doesn’t depend on types. In the car example I gave, methods defined in the car class manipulate generic cars no matter what type of car they are. All of the subclasses of car can, drive forward, drive backward, stop, etc. So since I can trust that the methods in the superclass car will be in all of the subclasses, I can send commands to the car object and let it sort everything out.

The code in car is then not effected in anyway when I create a new subclass. I also don’t need to know how the methods work, I can just trust that they will. On top of that I won’t have to change the car class code and potentially break other parts of the program. If a method in the car class doesn’t work for my subclass, I override the method in my new subclass, not the code in the superclass car.

If you don’t quite get it comment below and I’ll add more examples.

Overloading Methods

Jim the programmer has a problem with people trying to send string variable arguments to his addNumbers() function. Wouldn’t be great if you could create methods that were smart enough to work with whatever is sent to them? It would allow someone to send the number 4 stored as a string and the function would except it, convert it into a number type perform the addition and then send it back. You can with Method Overloading!

All you do is create multiple methods with the same name, but either a different return type, number of arguments, or type of arguments. Note: Some languages such as Javascript don’t allow overloading because they don’t assign variable types to the variables). Here are some overloaded methods:

int addNumbers( int numberOne, int numberTwo ) { …code… } // Accepts 2 integers, returns 1 integer

string addNumbers( string numberOne, string numberTwo ) {…code…} // Accepts 2 strings, returns 1 string

You can define as many overloaded methods as you want as long as you change the return type, or the arguments in anyway.

Polymorphism on Steroids

To finish this whole tutorial, I have to break something to you. Every object you will ever create comes from the same mother! That’s right. Every object has the same ultimate superclass named Object. So every class you ever create is extending the class Object. The class Object will have different variables and methods depending on the language you are using so I’ll skip over that. It’s not that important anyway.

So why don’t we just have everything defined as type Object and stop creating new classes? First off your code would be very confusing. More importantly you wouldn’t be able to access your methods. Above when I created the class dodge of type car, I had to define the method named tuneUp inside of the class car. I did that because you can only call an objects method if the class you are referencing has that method.

So is it possible to create a superclass that has all of the methods and variables you need to take advantage of Polymorphism? Yes and it is called an interface. An interface is just a shell class that provides the names of all of the variables and methods, but no code. Here is an example:

interface Vehicle {
var engine;
var gasTank;
var door;

driveForward(var howFar);
driveBackward(var howFar);
stop();
openDoor();

getGas();
getGasTank();
}

That’s how you define an interface. You describe what other classes will do with it, but don’t describe exactly how. That way you have the ability to use Polymorphism, without all of the problems.

That’s All Folks

Well that is Object Oriented Programming. I left out language specific issues so that you weren’t completely confused, but I covered the most important parts. I plan on creating tutorials on PHP, Objective C and maybe Java in the future. Check out my Javascript tutorial, to see what I’m doing right now.

If you have any questions leave them in the comments form below.

Till next time…

10 Responses to “What is Object Oriented Programming”

  1. supprof1 says:

    thank you derek.
    your tutorials are so good
    and in your website we can find all what we need

  2. Rick says:

    Derek is your name? Derek I think your information is definitely informative but I’m wondering can you do anything with volume of your recording? The recording of the videos are very low. Can you find away of making your recordings louder? Anyway keep up the good work and can you offer a series of building a website from scratch using HTML5 and demonstrate all its new capabilities? Thanks

    • admin says:

      Hi Rick

      I’m sorry, but some of my old videos had bad sound. It took me awhile to make higher quality videos. I think you’ll like my newer ones. I plan to cover html5, but I got side tracked. Here is a tutorial on canvas in html5 HTML 5 Help

  3. Zafar says:

    Excellent tutorials. Thank you very much!

  4. areeba says:

    Excellent tutorials..Sir,thank you so much for making these awesome tutorials.Please can you help me by making android development video tutorials?i really want to learn to make android development applications. Once again thanks alot…

    • admin says:

      I’ll see what I can do. They are easy to make, but I’m trying to find a cheap android device so I can properly test everything. I may just make the tutorials without one?

  5. Brad says:

    Hi there admin, love your site here! Been looking for something to the point like this for too long. I’m currently scouring the www for tutorials on REST and any tips/info on working with an api. From what I’ve read, I see that you’re not so keen on the Amazon affiliate program. I am attempting to use their product api to create a seller web service, and maybe make some money with their affiliate program on the side, but still not connecting all the dots, still new in the programming world.

    As I am understanding it now, I use can use REST to make the request to their database through an http/https url. I then get information back containing the attributes that I requested in XML format, then I display that information on my site from the client request.

    I guess I’m looking for a walk though on developing a simple site that can accept user data, configure that into a request, make the request, receive the response, and manipulate the data to display to the client.

    I could be asking way too much here, or maybe not enough? but any tips would be great. Thanks for all your work on newthinktank.com, I’ll be a frequent visitor. Hope your making lots of money off your efforts!

    • admin says:

      Hi Brad, Yes I don’t care for affiliate marketing with Amazon. I sent way to much traffic their way and received nothing in return. I am going to cover restful services in depth in the future. There is so much to cover and don’t forget about all of the awesome Twitter tools you can make and the ad revenue you can generate by supplying a useful tool that drives a TON of web traffic!

      Thank you for the request and because of the demand I’ll cover this topic very soon – Derek

Leave a Reply

Your email address will not be published.

Google+