In the book The Well Grounded Rubyist (excerpt), David Black talks about the “Class/Object Chicken-and-Egg Paradox”. I’m having a tough time understanding the entire concept.
Can someone explain it in better/easier/analogical/other terms?
Quote (emphasis mine):
The class
Classis an instance of itself; that is, it’s aClass
object. And there’s more. Remember the classObject? Well,Object
is a class… but classes are objects. So,Objectis an object. And
Classis a class. AndObjectis a class, andClassis an object.Which came first? How can the class
Classbe created unless the
classObjectalready exists? But how can there be a classObject
(or any other class) until there’s a classClassof which there can
be instances?The best way to deal with this paradox, at least for now, is to ignore
it. Ruby has to do some of this chicken-or-egg stuff in order to get
the class and object system up and running—and then, the circularity
and paradoxes don’t matter. In the course of programming, you just
need to know that classes are objects, instances of the class called
Class.(If you want to know in brief how it works, it’s like this: every
object has an internal record of what class it’s an instance of, and
the internal record inside the objectClasspoints back toClass.)
You can see the problem in this diagram:
(source: phrogz.net)
All object instances inherit from
Object. All classes are objects, andClassis a class, thereforeClassis an object. However, object instances inherit from their class, andObjectis an instance of theClassclass, thereforeObjectitself gets methods fromClass.As you can see in the diagram, however, there isn’t a circular lookup loop, because there are two different inheritance ‘parts’ to every class: the instance methods and the ‘class’ methods. In the end, the lookup path is sane.
N.B.: This diagram reflects Ruby 1.8, and thus does not include the core
BasicObjectclass introduced in Ruby 1.9.