Now I need help understanding what exactly happens when this code is called twice.
Ex: Car batmobile = new Car();
Will two objects get created?
A Car
object will be created each time that line is executed, so if you execute it twice, yes, two objects are created.
If so what happens to the first object.
If nothing else has a reference to it, it becomes eligible for garbage collection by the JVM. When and whether that happens depends on many factors within the JVM's garbage collector.
Can someone explain in detail what happens in terms of class,object and reference.
Car batmobile
...declares a variable of type Car
. Because it's an object type, the variable will end up holding an object reference (or null
, which means it's not holding a reference to any object). The actual object exists independently of any variables that may have a reference to it (and there may be many references to one object). An object reference is like a memory address saying where in memory the object is. (It is not a memory address, but it's like one.)
new Car();
...creates a new Car
object and calls the Car
constructor to initialize it. So:
Car batmobile = new Car();
...declares a variable, creates an object, calls the Car
constructor, and assigns a reference to that object to batmobile
.
Is this an infinite loop?
It would be, but eventually you'll run out of stack space, so it's a stack overflow error. That line calls the Alphabet
constructor, which calls the Alphabet
constructor, which calls the Alphabet
constructor... You get the idea.