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 ...

Get Learn to Program, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.