When we first learned about classes and relationships, I struggled to grasp the difference between Class and Instance Methods. It was frustrating not having a clear understanding of these two methods. I constantly called instance methods on a class and wondered why I kept getting errors.
Class Method Vs Instance Method: In a short simple definition, class methods calls on the whole class, while instance methods calls on an instance of a class.
In this example, we are using the class to call on the class_method.
However, we cannot use the class to call on an instance method directly.
To call an instance method:
In the example below, an error is given when you call an instance method on a class. You cannot call an instance method on a class like you can with class methods.
To call this this instance method. We would need to store an object in a variable, then call on the instance method with that variable, like so:
Song class example:
In this example, @@all is indicated as a class method. Macros are set up for name, genre, and artists which are instance methods.
Let’s make some songs!
I stored the new songs in a variable to make it more accessible when we need it. For now, we have a few songs stored in our Song class. What if I wanted to see all my songs? This would be a great way to utilize our class method! Since we need to view all objects stored in class, we would need to call on the whole class to return all songs that were stored in this class. Remember class methods call on the whole class!
So it would look something like this:
Now we have all our instances displayed (or all our songs).
What if I wanted just to get the name of one song from all our songs? We would have to use an instance method! In this case, we would use our name method to get the name of this first instance. But wait! This is an instance method. So we can’t use Song.name! Think about it. The class of Song has more than one song stored in it. How will it know which name I want to return? This is where we use our variables to call on our instance methods.
Now we have just the name of a single instance, using an instance method!
Top comments (0)