This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach 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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
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: 37884
    
  22
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: 19649
    
  18

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
How To Ask Questions How To Answer Questions
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: can we create in the same class
 
Similar Threads
final methods
inheritance n inner classes
Overload
can method overriding be done from the same class?
Doubt in john meyers' question...