So why does the foll code doesnot give any exception although e points to object of same class??
Your original code created a new Animal object every time that an Animal object was created. Your new code only creates a new Animal object if you call the foo
method. You call the foo
method on the first Animal that you create, but you don't call foo
on the second Animal (the one that you create inside foo
). So it stops there and no infinite recursion happens. If you added the line e.foo()
inside your foo
method, you would get infinite recursion again.