new vs. initialize

That’s some pretty cool stuff we just covered. But the relationship between new and initialize is a bit subtle. And “subtle” may as well mean “confusing.” Just what is the deal?

The methods new and initialize work hand in hand.  You use new to create a new object, and initialize is then called automatically (if you defined it in your class). They pretty much happen at the same time. How do you keep them straight?

First, new is a method of the class, while initialize is a method of the instance. You use new to create the instance, and then initialize is automatically called on that instance. This means that the call to new must come first! Until you call new, there’s no instance to call initialize upon.

Second, you define initialize in your class, but you never define new. (It’s already built in to all classes.) Conversely, you call new to create an object, but you never call initialize. The method new takes care of that for you.

(Strictly speaking, it is possible to call initialize, just as it is possible to define new. But doing so is either very advanced or very stupid. Or both. Let’s not even go there.)

The reason for having these two methods is that you really need one of them to be a class method and the other to be an instance method. If you think about it, new has to be a class method, because when you want to create an object, the object you want does not exist yet! You can’t say, for example, the following:

die.new

because die doesn’t exist yet.

And initialize really has to be an instance method, because you are initializing that object. This means that you need access to the instance variables and such.  You can’t do that from a class method, because it wouldn’t know which instance to get the instance variables from. (You certainly don’t want to initialize every single instance of Die every time you create a new one.)

So just remember, you define the instance method initialize, and you call the class method new (and not the other way around).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.63.191