File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Creating Own Object in Method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Creating Own Object in Method" Watch "Creating Own Object in Method" New topic

Creating Own Object in Method

Debojit Sinha
Ranch Hand

Joined: Mar 13, 2010
Posts: 66

Hi, people,
Why is it legal to create object of own class from a method?
Thank You.
Yogesh Gnanapraksam
Ranch Hand

Joined: Dec 17, 2009
Posts: 133
I don't understand your question.
Do you mean to say that it should not be allowed ?
pankaj vijay
Ranch Hand

Joined: Apr 01, 2008
Posts: 75
Give me a reason why should be it illegal ???

Pankaj Vijay (SCJP, SCBCD)
Learn Core Java,Learn Servlet Jsp, SCJP Questions,Struts Tutorial
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15045

Do you mean something like this:

There's nothing wrong with creating any kind of object in a method, including an object of the class that the method is in. Why do you think it's strange that this is legal?

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Debojit Sinha
Ranch Hand

Joined: Mar 13, 2010
Posts: 66

Er, I think I phrased the question incorrectly, sorry.
My point was that since classes are created at compnile time, and, if a constructor to itself is called within it, should not here be an error? Since, after all, the class to be constructed is not in existence yet. In all probability I am wrong, and look forward to your clarification. Thank You.
Rob Spoor

Joined: Oct 27, 2005
Posts: 20193

You mean something like this:
That will cause a StackOverflowError yes.

How To Ask Questions How To Answer Questions
Debojit Sinha
Ranch Hand

Joined: Mar 13, 2010
Posts: 66

Sorry I took so long to answer, project lead was being a nazi, but thanks for the help.
I agree. Here's the link:
subject: Creating Own Object in Method
jQuery in Action, 3rd edition