In an interview I was asked why are objects in java created dynamically?
I can't understand this question, can any body explain this?
The person could be referring to the fact that Java does not know implicit object creation on the stack like C++ does.
std::string string;
Creates an object on the stack in C++ while
String string;
just creates a reference in Java, but no object is created (and no constructor called).
If you are interested about that topic I suggest to read more about Java's memory model.
It seems to me that the question asks why objects in Java are created only with dynamically allocated memory (using the new
keyword) as opposed to being created with statically allocated memory as well (like in C++, for example). If (and it's a big if) this is what the question meant, there are some things you can answer to that.
Before answering, one must note that the premise of the question is not entirely right (you could even say that it's wrong). Java objects aren't created strictly dynamically. If escape analysis can prove that a reference doesn't escape a given scope, it may be compiled so that it uses static allocation.
Given the above, one possible answer is abstraction. The stack and the heap (which are traditionally associated with static and dynamic memory, respectively) are in fact implementation details (even if we are so used to them). Java attempts to hide that and thus it doesn't give you terms like static or dynamic memory to work with - it doesn't even give you memory, it gives you objects.
Another answer (again, given the note) is the real world usage of objects. A lot of the time in real world scenarios, objects do need to escape their initial scope, making dynamic allocation the only valid candidate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With