Designed by Graphiqastock

The ULTIMATE NOOB GUIDE to understanding Object Oriented Programming

Shares

I started my programming journey learning the wonderful language of JAVA, which is known as an Object Oriented programming language, sometimes seen as OOP. Object Orientated programming is everywhere! Tons of other languages are Object Oriented, like Python, JavaScript, C++, C#, Ruby, the list goes on. So WHAT exactly is it? And HOW is it used? Well, this post aims to provide a solid foundation of Object Oriented programming presented in an easy to understand way. So that even a complete beginner can get it.

Just a quick note before we start. I will include coded examples in this post, but I have written them in Java. So please be aware that other Object Oriented programming languages won’t look exactly the same as these examples. However, I feel it is important to include examples because the principals are the same, and it will still give you a good idea of how Object Oriented Programming works.

Background vector created by Blossomstar - Freepik.com

Let’s start with a little introduction to Object Oriented Programming

Object Oriented Programming is centered around the creation and use of virtual objects i.e. objects that don’t exist in the real world. These objects can be thought of in that same way as any other real-world objects.

Now, there are two major characteristics of objects, which are fundamental to OOP. And they are Attributes and Behaviors.

Attributes – The physical makeup and state of the object. For example, a car HAS wheels, doors, an engine, a steering wheel etc.

Behaviors  – The actions that an object can perform. Again, with the car example, a car CAN accelerate, brake, turn etc.

Simply, think of what an object “HAS”, and what it “CAN” do.

In programming speak, we refer to attributes as an object’s variables, and behaviors as an object’s methods. Don’t worry, I will explain if you need me to!

If you have already had a taste of programming you may already be aware of what variables and methods are. And if that’s the case you can skip to the next section.

But for those who are not sure, here is a quick crash course.

What are variables?

To summarize, a variable is a container to store useful information. This could be a number, letter, word, sentence, true or false statement (referred to as a “Boolean”), or even another object! But for now, don’t worry about other objects, we’re going to keep it simple!

And for the purpose of simplicity, we are going to say that we have a variable called “Name” and we want to store the word “Owen” in it. Well, it’s as easy as saying:

Name = Owen

Now the variable called “Name” stores and represents the value of “Owen”. For the record, this is not written in a programming syntax i.e. code speak. It’s only to illustrate the basic point. But in case you were wondering, here is what that would look like written in Java:

Three things to mention:

  1.  The semicolon, this weird thing “;” at the end, just denotes the end of a statement. Kind of the same way we use a “.” at the end of a sentence. However, not all languages use them. For example, Python doesn’t.
  2. The word String refers to the data type, which lets the variable know what type of data we want to store. A type of data could be a letter, word, true or false, number, or decimal. In this example String means a word, so we want to store a word in the variable “Owen”.
  3. Because the variable is of type String we have to surround the value, “Owen”, in quotes. This does not need to be done with any other data type.

For reference the common types are:

  • int – stores a number
  • float = stores a decimal commonly called a floating point number
  • boolean – stores a “true” or “false” value
  • char – stores a letter i.e. a character
  • string – stores a word or string of words

In relation to objects, we create object variables, known as member variables to store data. These member variables tell us specifics about what the object HAS. Variables need to be unique so that the specific data contained can then be retrieved, displayed and manipulated by methods, which brings us to the next question…

What is a method?

At its basic level, a method is a series of steps outlined in an object, which tells said object e.g. a car, to do a certain thing e.g. drive.

These steps are all neatly packaged in a contained block of code, normally represented by “{}”. It’s this block of code that tells the object to stop being lazy and DO SOMETHING! But before we can tell it to do something we need to be able to reference it, so like a variable we give it a name.

At a rudimentary level, you can imagine if we had a method named “turnEngineOn”, designed to, can you guess? Yes, turn the engine on. It may resemble something like this:

* The text after “*” is just a comment added for context.

turnEngineOn      *this is the name of the method
{
Turn the car engine on      *this is the code that makes the object “do something”
}      

A few things to note here:

  1. Again, this is not programming syntax, it’s just for visual representation.
  2. The name looks weird because it is written in what’s called “CamelCase”, which is the generally accepted way to write a method for readability.
  3. I have surrounded “Turn car engine on”, these bad boys”{}”, because typically blocks of code in methods are contained within curly brackets.

There is more to a method than this, but it illustrates the basic structure. However, below I have tried to give the full picture, and I have done my best to keep it simple!

Generally speaking, a method will have 4 main parts; a name, parameters, body, and a possible return value.

Name – The same way a variable need a name, a method also needs a name. This allows us to refer to that specific method in the object to say “we want the object to do this”. Typically this is known as “calling a method”.

Parameters – It’s a fancy way to say brackets, you know these things “( )”, the normal none curly ones. Parameters follow the name, and are the location where you pass data in the form of variables to your method, should it require it.

A method may not need any data. For example, if the method is updating, or setting the value of an objects member variable e.g. changing our “Name” variable from earlier to equal “Tim” instead of “Owen”, then the parameters may be empty. Parameters tend to be used to interact with another object or to use external data in the methods step by step instructions.

Body – The body follows the parameters and is that block of code surrounded by “{}”, which I mentioned earlier. This is the powerhouse, those series of operations, which result in your object doing something.

Return value – Your method may return a value, for example, a number, text or even an object. This just means your method will spit out some form of result once it reaches the last step. It’s like being handed all the ingredients to make an apple pie, making it, and handing it back. However, methods don’t always have a return value. If your method performs a calculation or creates something meaningful, which you need somewhere else in your program, then a return is necessary.

For reference here is an example of a simple method called “returnMyName” written in Java:

Let’s break this method down…

  1. First, we have the word “public”, don’t worry too much about this now. “Public” is a keyword know as an “Access Modifier”, which we will cover later in this post.
  2. Second, we have the word “String”. This is where we specify the data type to return. And as we want to return the variable “myName”, which is a String, we put “String” after “public”. If we don’t want to return anything we can add “void” instead of “String”.
  3. Next up we have the name, which is pretty self-explanatory and as you can see demonstrates camel case, which we have already covered.
  4. After that, we have the parameters i.e. brackets…these things “()”. As you can see they are empty, and that’s because we don’t need to pass any outside data to this method. Although we could have. And in fact, I could have written: “(String name)”. So rather than setting “myName = Owen;”, I could have put “myName = name;”. This would have taken whatever word was set as “name” in the parameters and put it into the variable, “myName”.
  5. And finally, in the body we set the variable value, then use the keyword “return” to say we want to return the String “myName”.

Background vector created by Blossomstar - Freepik.comBack to Object-Oriented Programming with some quick terminology 

I am sure you are probably interested to see what an object actually looks like when it’s written in code, and how it all works. And I promise I have examples so you can fully understand. But there are a few basics terminologies we need to cover first just so you are not completely confused like I was!

Those few things are “Classes”, “Constructors”, “Declaration”, “Instantiation”, “Initialization”, and “Instances”. I know they sound scary but don’t worry. Here’s another little crash course to give you a basic understanding.

Classes

A class is essentially a file that holds the blueprint for building an object. It includes a description of how the object should look (attributes) and behave (methods), plus instruction on how to build it (the constructor). You wouldn’t build a house without first having a blueprint, and the same applies to objects. Therefore every object will first start its life as a class. You will see full examples of a class at work later, but for now here a little taster:

First, we specify that we are creating a class using the word “class”, then we give the class a name. Again, dont worry about the word “public” we will get to that when we talk about Encapsulation. It sounds scary, but it’s not.

Constructors

We have the class, aka the blueprint, but how does an object actually get built? Well, that’s the job of the constructor.  This little guy is a method, which set the values of an objects member variables (attributes), which describe the object so that it can come into being. The constructor specifies the information it needs, then applies it.

As I said, the constructor is a method so it looks very similar. The main difference is that it shares the name of the class. So this example will be the constructor for the class, “Person”.

Here’s the example:

As you can see the parameters, aka “()” are populated with variables. These variables get passed to the body, i.e. the code between “{}”. At which point they are used to set the member variables of the object upon creation. This essentially brings the object to life.

Declaration

The first step to actually bringing an object into life, metaphorically speaking, is to “declare” it. Basically announcing to the world, or more importantly the program, what class we want to create our object from this class, then give it a name. For example, we have a class called “Car”, so we want to first announce that we are creating a Car object, which we are then going to name Tesla Model X.

Instantiation

Once we have declared the type and name of object we wish to create, we need to get the ball rolling by letting the program know that we are creating a completely NEW object. This is normally done simply by writing the keyword word “new” and it’s what programmers mean when they say “instantiate”. Basically, just start creating this new object. And here’s an example:

Initialization

After we’ve said we want to build a “new” object, we need to supply any information, which may have been requested by the constructor of the class. For example, in the contractor of our Car class, may have asked for the number of wheels, number of doors, colour of the car etc. This information get’s added into parameters (brackets) and is passed into the constructor so it has all the information to build the object. Here’s an example, assuming the car has 4 wheels, 5 doors and is black.

*Because the colour is of type String we put “” around it. However, we don’t have to do this with any other data types.

Instances

Once an object has been created we can now refer to it as an “instance”. This is a single reference to a unique object. To put this a better way, you can have several car objects, one called “Mustang”, one called “Model X”, and one called “Porsche”. Each of those is a single INSTANCE of a car object.

Example time – What does an OBJECT look like in actual code?

So the idea of an object is pretty straightforward, it CAN do certain things, and it HAS certain things. But how does this all translate into real code? Well, I have created some examples below, with explanations to help you understand.

I am aware that I’ve used a lot of car examples! So to switch things up I’m going to imagine that I’m creating a game, in which I am going to need to create a “Player” object.

This will be a very simple example just to illustrate the concepts and structure of an object. If you get stuck I suggest going back and looking at some of the previous explanations and examples.

We create an object in 2 steps, first we create our blueprint and then we construct it.

Step 1

The first step is to create a “Player” class, and hopefully, now you know what a class is.

Context for above code:

  1. We define our Player class using “public class Player{}”.
  2. We move into the curly brackets and specify all the member variables (attributes) of the Player class i.e. name, health, weapon.
  3. We create our constructor and mention the variables we want to pass through the parameters “()”, in order to set the objects member variables. Remember the objects member variables are denoted using “this.”. See above section on what a constructor is if you’re unsure.
  4. We add a method (behavior) called “attack()”, which uses this Java method “System.out.println()” to display “Player has attacked opponent” when the method is used.

Step 2

Now we have created the class, or in other words the blueprint for our Player object, we can begin building it and doing stuff! And to do this we have to start writing some code in the “main method” which is traditionally located in the “Main class” file.

The main method is the entry point for your programs and is what executes your code. Basically, the main method takes your code and brings it to life. Normally when a new project is created in your Integrated Development Environment (IDE) it will automatically generate the Main class and main method for you. How thoughtful!

So lets being…

Context for above code:

  1. A new Player called “PlayerOne” is declared.
  2. We then instantiate the object with the “new” keyword.
  3. The new object, “PlayerOne” gets initialized with the values “Owen”, “100, “Sword, which represents the name, health, and weapon.
  4. An instance of Player called “PlayerOne” has now been created and we can now tell that object to attack by writing “PlayerOne.attack();”. For reference, an object’s methods are executed by first specifying the instance (object), then adding a “.” followed by the method name.
  5. The “attack()” method has been called so PlayerOne now executes the code i.e. the steps by step instructions outlined in the “attack”()” method. In this example, the action we described was for the statement “Player has attacked opponent” to be displayed.

And that the basics of creating an object! See it’s not that bad. Now let’s look at some fundamentals principals of Object-Oriented Programming.

Let’s dive into the 5 main principals of Object-Oriented Programming 

Background vector created by Blossomstar - Freepik.com

1. Inheritance

Here’s a quick summary, and don’t get scared off, I will simplify this in a second!

So, inheritance describes the relationship between two classes, and often this relationship is thought of in a parent and child dynamic. Therefore, it’s very common to hear the words “Parent class” and “Child class”. Essentially, the child will inherit behaviors (methods) and attributes (variables) from the parent. In programming terms, this means methods and variables are shared from the parent to the child. And because this is the case, we can access methods and variables in the parent from the child. This allows us to reuse code.

I think the simplest way to think about inheritance is as an “is-relationship” between two classes. This is to say one class “is” a type of another. So a car “is” a type of vehicle, a dog “is” a type of animal and a flower “is” a type of plant. And here’s how that would work looking at the animal scenario.

Step 1 – First, we have to think about our parent class, which will be our “Animal class”. This will be the base class which all other animals will descend from (inherit from).

Step 2 – We begin by listing all the common behaviors and attributes that animals share and add this to our “Animal class” in the form of method and variables. For example, all animals have a head, body, can eat and breath etc.

Step 3 – Next our child class, which will be the “Dog class”. And like any animal, it will have all the same characteristics. However, a dog also has legs, a tail, and barks. So these will additionally need to be added as variables and methods.

Step 4 – Finally, we can create a parent and child relationship between the “Animal” and “Dog” classes using inheritance. This will give the “Dog” class access to the variables and methods in the “Animal” class, which eliminates the need write the same code that defines a dog as having the ability to eat and move etc.

Here’s an example in code:

2. Composition

Composition basically means building an object from other objects. And when you think about it, the word “composition” means the physical make up of something, or for lack of a better word, it’s ingredients.

Where inheritance is considered to be an “is-relationship”, composition can be thought of as a has-relationship. What is an object made of? Or what does it have? Let’s revisit the car example. A car “has” an engine, steering wheel, doors, gearbox and so on and so forth. All these things are objects in their own right.

Composition allows us to build more complex and fully formed objects, but how do we do this exactly? Well, you may have already noticed all the things that make up a car can be considered as attributes i.e. variables! So it’s simply a case of constructing a class that includes the necessary objects as it’s member variables.

And again, like inheritance, composition gives us the ability to reuse code because the objects that make up the overall, all share their behaviors (methods) and attributes (variables) with that overall object. So if the car object wanted to access a method in the engine object, called “startEngine”, it’s more than welcome too.

Here’s an example in code:

3. Encapsulation

Encapsulation is all about protecting classes by hiding or restricting access to its components i.e. it’s variables and methods. It’s like having a security system so your average Joe can’t just waltz in and start messing around with your stuff. But rather than it being your average Joe who restricted its other classes or code.

There are standard parts of a class that we don’t want public to every Tom, Dick, and Harry. A typical example is the member variables of a class which describe the attributes of an object. It’s very common to restrict access to an objects member variables to that objects own methods. These methods are commonly named “Getters” and “Setters”, which fall into the category of “Accessors” and “Mutators”. More strange terminology! Don’t worry, I’ll explain.

A Getter method, know as an Accessor –  Is a method that “gets” the value stored in the objects member variable and spits it out the form of a return somewhere else. Refereed to as an Accessor because it can “access” parts of the object.

A Setter method, know as a Mutator  – Is a method that “sets” the value of an objects member variable. Referred to as a Mutator because it can change or “mutate” parts of the object.

Why do we want to do this you ask? Great question! A valid reason for restrict access in this way is because if those variables were public. Then technically they could be accessed and changed from anywhere. And if for some reason a mistake was made that changed the variable in a way that was unintended. That mistake could again, be anywhere! At least if it’s restricted to the class we only have to look in one place.

This isn’t so much of a problem when you have a couple of lines of code. But when you have thousands, it can be a real headache trying to find the culprit!

Basically, it’s to limit access so we can maintain CONTROL over our objects. And therefore, reducing the chance of them being changed in unexpected ways.

By now you may be asking “how do we restrict access?”. Well, we use what’s called “Access Modifiers”. These are keywords which precede variable and method names to denote the level of access available to outside code. The 3 main keywords are:

Private – This means that only the current class will be able to access the variables or methods.

Protected – This means only the current class and any child classes will have access to the variables or methods.

Public – This means the variables or methods are open and can be accessed anywhere.

Here’s an example in code:

4. Abstraction

In life when we say something is abstract, we generally mean something that is a thought and has no concrete existence. We have a rough idea of what this thought is but not the details of how it looks and interacts with the world.

Abstraction in Object Oriented Programming is the same concept. We define all the things that an object has and can do without specifying any of these. The object only exits as an idea until another class comes along to fill in the details.

An example, we can create an abstract class called “Animal”. And like a normal class, it will outline the variables (attributes) and methods (behaviors) associated with animals. However, once the names of these methods and variables have been defined no further detail is added. So the code, which actually sets the variables and provides the step by step instruction for the method, is left BLANK.

Only when we create another class e.g. a “Bird” class, to inherit from Animal, do those variables and methods get filled in.

Abstraction is really useful for ensuring the correct use of our classes by forcing methods to be implemented. What does this mean? Let’s continue with the animal example. All animals must eat, otherwise, they die. And because “Animal” is an abstract class it will force the “Bird” class to use the eat method, so now our bird won’t die!

A child class that inherits from a normal (non-abstract) parent class is under no obligations to use its methods.

Abstraction is also considered to be closely linked on Encapsulation as the complexities i.e. the details of the class are hidden. Remember it just defines what the object does, not how it does it.

In Java, we make a class abstract by using the keyword “Abstract”. Here is an example in code:

5. Polymorphism

Let’s start out with the meaning of this strange word. So, what does it mean? Well, Polymorphism means one name, many forms. I know that sounds very cryptic! But essentially its referring to how the same method can be adapted to perform different actions. Hence the “one name, many forms” thing.

Polymorphism is closely linked to inheritance as it involves the child class redefining the behaviors (methods) of its parent.

In essence, you can have multiple objects, which inherit from the same class and all those objects can appear with the same methods. However, those methods may all do different things, even though they are all built from the same blueprint. How is this possible you may ask? In two way…

Polymorphism comes in two main forms, Overloading and Overriding. To make it easier I like to think of Overloading as the copying of methods and Overriding as the taking control over methods.

Overloading – Is having multiple methods with the same name, copies if you will. And each one asking for different information to be passed into its parameters aka brackets. You may have one method called run(), where nothing is in the parameters, and another called run(speed), where a particular speed is given.

Overriding Is the ability of a child class to take control (override) of a method in its parent class and change the action (implementation) it performs. The method will still have the same name but now can perform a different action.

Here’s an example in code:

Well, those are all the basic principals and fundamentals of Object Oriented Programming. I hope this has been useful and not too confusing. Once you understand the basics, you will soon be on your way to building much larger more complex objects. But just remember the principles taught here. They will serve you well. Go forth and conquer!

Feature image designed by Graphiqastock

Sharing is caring!

About the Author Owen

Creator of Code Dad, father and self-taught programmer. My mission is to balance life, work, family, all while learning to code, and hopefully help others who want to do the same.

follow me on: