This week's book giveaway is in the Other Languages forum.
We're giving away four copies of Functional Reactive Programming and have Stephen Blackheath and Anthony Jones on-line!
See this thread for details.
Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

can we create in the same class

 
Tomendra Singh
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all'
i just want to know that can an object of any class can be created in the same class, if it is? please provide me how?
 
Campbell Ritchie
Sheriff
Pie
Posts: 50241
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not quite sure about your question, but the answer is probably "yes."

You can have a linked list made up of nodes, each with a reference to the next node on the list. This is sometimes called a self-referential class.
 
Rob Spoor
Sheriff
Pie
Posts: 20667
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just make sure you don't do that in the constructor (with the same parameters) or directly from the declaration of an instance field or you will get a StackOverflowError:

If we change the first constructor to the following it will also go wrong:

This is because in all examples documented as problematic, creating a new Test object results in the creating of a new Test object. Which results in the the creating of a new Test object. Which results in the the creating of a new Test object. This will continue until a StackOverflowError is thrown by the JVM.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic