Win a copy of Java 9 Modularity: Patterns and Practices for Developing Maintainable Applications this week in the Java 9 forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Question about no of objects & references  RSS feed

 
Kishore Dandu
Ranch Hand
Posts: 1934
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Following is a qn from one of famous books:

Code:
Thing item, stuff;
item = new Thing();
Thing entity = new Thing();

Qn: how many objects and references are created.

My answer: 3 objects and 2 references.

Actual answer: 2 objects and 3 references.

Can some one shed a light on this??
 
Nina Binde
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kishore, the following is the explanation:

Thing item, stuff;
item = new Thing();
Thing entity = new Thing();

You create an object only when you call the constructor of the class. Hence in the above statements, there are two objects created with the new operator. You create references when you declare the variables. In the above case, there are three references namely item, stuff and entity.

Hope that helps.
 
Kishore Dandu
Ranch Hand
Posts: 1934
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Nina Binde:
Kishore, the following is the explanation:

Thing item, stuff;
item = new Thing();
Thing entity = new Thing();

You create an object only when you call the constructor of the class. Hence in the above statements, there are two objects created with the new operator. You create references when you declare the variables. In the above case, there are three references namely item, stuff and entity.

Hope that helps.


thanks for that explanation.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!