DEV Community

Robin Vernon
Robin Vernon

Posted on

Instance Vs. Class

On introduction, the idea of instances and classes can seem overwhelming. However, they are actually quite simple concepts to understand over time. Let’s take a step back, and look at them in another light.

What is a Class?
A class is in practice, a blueprint while an instance is a single occurrence of a class. Let’s think about it like this, when creating a table for a car class, I might say it has a make, model, color, and a year. These attributes would be defined in our table and permitted in our create method. These blueprints aren't the actual car, instead they lay out step by step what every car should consist of and give us other helpful information (Class Methods) to be used in creation.

What is an Instance?
An instance is the product of a class. For example, an instance of our Cars class could be a black 2019 Dodge Charger. Another instance could be a 1993 red Chevy. These are all single occurrences of the cars class, all following the specific blueprint we created. These instances are all unique in value, but they still share the same attributes. If we were to strip the instances down to their very basic mold, they have a make, model, color and year. This is how the blueprint is used.
How to create an instance:
Using our previous Car class and assuming string types for all except year, we could use .create
Car.create(make: "Dodge",model: "Charger",color: "Matte Black",year: 2015)
or we could assign an instance to a variable:
assuming we have setter and getter methods in our class file
attr_reader :make, :model, :color, :year
we could go the following in our rails console
my_new_car = Car.new
my_new_car.make= "Dodge"
my_new_car.model= "Charger"
my_new_car.color= "Blue"
my_new_car.year= 2015

Image description

Which way do you like more? Open to feedback.
check out my github to see which method I like most:
https://github.com/robinlashae1

Top comments (0)