Table of Contents
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
class Coffee DEFAULT_SUGAR = 3 DEFAULT_STRENGTH = 3 def initialize(sugar = DEFAULT_SUGAR, strength = DEFAULT_STRENGTH) @sugar = sugar @strength = strength end def add_sugar(sugar) @sugar += sugar end def strengthen(step) @strength += step end def self.create_10(sugar = DEFAULT_SUGAR, strength = DEFAULT_STRENGTH) return self.create_many(10, sugar, strength) end private def self.create_many(count, sugar = DEFAULT_SUGAR, strength = DEFAULT_STRENGTH) coffees = [] for i in 1..count coffees.push(Coffee.new(sugar, strength)) end return coffees end end |
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.
1 |
coffee = Coffee.new(1, 3) |
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.
1 2 3 4 |
Coffee.new(1, 3) Coffee.new(1, 2) Coffee.new(2, 3) Coffee.new(3, 3) |
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.