This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes can we create in the same class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "can we create in the same class" Watch "can we create in the same class" New topic
Author

can we create in the same class

Tomendra Singh
Ranch Hand

Joined: Jun 28, 2008
Posts: 47
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?


Strength Is Life,Weakness Is Death- Swamy Vivekanand.
SCJP 5.0(87%)
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 43892
    
  32
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

Joined: Oct 27, 2005
Posts: 20077
    
  30

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6
How To Ask Questions How To Answer Questions
 
Have you checked out Aspose?
 
subject: can we create in the same class
 
It's not a secret anymore!