Tuesday, August 13, 2013

How many objects are created when you create an object of a plain class?

This is shared out of a random thought. Let’s say we’ve got two classes:
class A{}
class B extends A{
 static B obj = new B();
Do not read further until you have the answer to the question.

Well, at once, I too thought that the number of objects created is 1. But then I pictured the memory areas for the classes. If you are caught unawares, check the memory tag. So, lets figure out how many objects are created:
1. One object created in our code
new B();
2. Apart from this, the class will be loaded in Method Area inside a java.lang.Class object. So, there we are with 2 objects.
3. Now since, the code will execute on a threading model, I can expect 2 more thread objects:
    3.1 Main thread
    3.2 Daemon thread for garbage collection

So now we have at least 4 objects but if we dig deep, we will come to know about many more objects created by the big-hearted JVM, but those are of not our concern at any cost unless we are studying underlying Java architecture.
Hence, most of the times we can just sign-off by telling that only one object is created because that’s user defined and we should be more concerned with that. And all of this just by His grace bestowed upon us via James Gosling.
Let me know how big a noob I am with your expert review comments! :-)

No comments:

Post a Comment

Liked or hated the post? Leave your words of wisdom! Thank you :)