• Post Reply Bookmark Topic Watch Topic
  • New Topic

Nested new(...new()) creation of objects  RSS feed

 
kambar bek
Greenhorn
Posts: 23
Eclipse IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I m used to see objects created in java like this:





questions:

what does it mean when we create object like in * - this nested thing?

can we do something like this:


DisplayTime x = new DisplayTime(new Calendar(new Player(new Gambler(new Weather(...............))))) - and so on?

if yes, how many times can we nest it? and what does it mean if i see 3 or more objects created, nested in each other?

i m really confused about what created where / who creates what

can someone explain?
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Erjan Kenjegalee wrote:


questions:

what does it mean when we create object like in * - this nested thing?


The above is equivalent to:


except that in your example we don't have a variable pointing to the Calendar object, so this bit of code cannot use it again after passing it to DisplayTime's constuctor.

Also note that if the Calendar here is java.util.Calendar, it's an abstract class so both of those snippets are illegal. They'd work with a concrete class thoguh.

can we do something like this:

DisplayTime x = new DisplayTime(new Calendar(new Player(new Gambler(new Weather(...............))))) - and so on?


Yes, as long as the constructors that take the args we're calling them with actually exist. We can't just pass any old arbitrary object, we have to use the signatures that actually exist.

if yes, how many times can we nest it? and what does it mean if i see 3 or more objects created, nested in each other?


The language may or may not impose a limit, either explicitly or as a side-effect of some other rule. If it does, it's far larger than you'd ever write in real life. Once you get beyond one or two levels, it gets hard to read, so you probably won't be nesting them that deeply anyway.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!