If you’re new to object oriented programming, a natural question to ask is: what does instantiation mean? Like many other concepts in the development world, instantiation is actually a relatively straightforward concept that suffers from having an overly complex name.
What Does Instantiation Mean: A Real World Example
Before we dive into the code, let’s analyze a real world example of instantiation. (And a quick spoiler alert. If you understand what it takes to build a house, you already understand instantiation.)
Let’s imagine that you’re building a house. One of the first tasks you’d most likely do is build a blueprint for the home. This blueprint would contain attributes and features of the house, such as:
- The dimensions for each room
- How the plumbing will flow
- And essentially every attribute of the house
Now let me ask a dumb question. Is the blueprint of the house the actual house? No, it simply lists out the attributes and design for how the home will be created
The Actual House
So after the blueprint is completed, the actual home can be built. Dare I say that the home can be “instantiated”?
Connecting the Dots
From an object oriented programming perspective, a class is the blueprint for an object. A class simply describes what an object will look like and how it will behave.
Therefore instantiation is the process of taking a class definition and creating an object that you can use in a program. Still a little fuzzy? That’s fine, let’s look at a code example.
What Does Instantiation Mean: A Code Example
I’m going to build this example in Ruby, however instantiation has the same behavior in essentially every object oriented language.
The Class: aka the code blueprint
For this example we’re going to have an
Invoice class. Inside the class definition we have attributes, such as a
total. Along with some behavior, such as printing out an invoice
Creating an Object: using instantiation
Now, we create a new instance of
Invoice and store it in a variable, as shown here. I have used instantiation to:
- Take a class.
- Build an object based on the class definition.
And with this process in place I can use the object to perform tasks, such as printing out the
So, at it’s core, instantiation is the process of taking a class, and creating an object from it that you can actually use in your program.
I hope that this has been a helpful guide for answering the question of how instantiation works, and that you now feel confident on using it in your own programs.
For a deeper dive into object oriented programming techniques, I’ve included a link to some tutorials on OOP in Ruby where you can extend your knowledge and build some real world projects. I’ve also included a link to the code I reviewed in this guide.