Difference between Class and Instance


These days, I explain the difference between class and instance as follows.

In the past days, I explained that Class is a design drawing. But it can’t explain static method, so I explained class as creating machine.

Class

Class is creating machine.

Instance

Instance is what the machine created.

Example

Take the following example class.

This is the machine which makes Coffee. Machine is only one. The machine has some functions. It’s like a coffee vending machine.

Make an Instance: new

Machine has the function to make a new instance. It is new method in Ruby. The procedure executed when the new function is run is written in initialize.

Machine’s new function creates a new instance. Coffee machine’s new method creates new coffee.

The initialize receives 2 parameters, sugar and strength. Both of them have default values. Machine is only one but many instance can be created and every instance is different from each other. Yes, all coffee output from coffee machine are different even if every sugar amounts are the same.

Every instance, coffee is different. Even if each sugar and strength are the same. Instance variable @sugar and @strength represent the character of the instance. Coffee’s sugar amount is defined for each coffee, instance, and can be differentiate. Each coffee’s sugar amount is saved in each instance.

Function of Machine and Instance

Apart from new function, above Coffee machine has the function to create 10 coffees at the same time, create_10 function. As if coffee vending machine has new button to make one coffee, and create_10 button to make 10 coffees.

When you write function like def self.xxxx, it will be machine function. self in it’s expression means machine itself. The function is machine function.

Function without self, such as def add_sugar, is coffee’s function.

And those coffee’s functions are coffee design drawing. Coffee machine contains functions of itself and the design of product.

Re-think Coffee Machine

DEFAULT_SUGAR and DEFAULT_STRENGTH, what I didn’t explained, are the design of coffee machine inside. If you change those values, it is like you tunes the machine.