GeeCON Prague 2014*
The moose likes Java in General and the fly likes Creating objects in the same class 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 objects in the same class" Watch "Creating objects in the same class" New topic
Author

Creating objects in the same class

Mukul Anand
Greenhorn

Joined: Nov 28, 2012
Posts: 29
What does it mean to create an object of a class in that same class??
I mean whats the logic??
harshvardhan ojha
Ranch Hand

Joined: Jul 26, 2007
Posts: 157
    
    1

In what context are you talking? Where did you found this??
This may be in context of some design pattern, some strategy to take control over constructors or factory methods. Please be specific.
Mukul Anand
Greenhorn

Joined: Nov 28, 2012
Posts: 29
well.. sometimes, an object of a class is created within the same class.. Usually, we create an object for a class in another class. Isn't it??
harshvardhan ojha
Ranch Hand

Joined: Jul 26, 2007
Posts: 157
    
    1

That depends on your requirement. Lets say i have class A


In both the cases object will be same, only visibility might be different, but that again is valid for access modifiers. The contents of object(i.e. members and variables) will be same.
I mean to say that, object of a class will be same, wherever you create it.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39067
    
  23
Are you thinking about singletons? Or factory methods?
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14193
    
  20

Mukul Anand wrote:What does it mean to create an object of a class in that same class??

It doesn't mean anything special; it doesn't matter if you create an instance of a class inside a method of that class, or inside a method of some other class.

Is there a specific scenario that confuses you? If so, then please provide a code example and we can explain what's happening.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Mukul Anand
Greenhorn

Joined: Nov 28, 2012
Posts: 29
Nothing specific.. but, I used to believe that an object of a class is and should be made in some other class. So, when I noticed this for the first time, I got confused.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39067
    
  23
There can be good reasons why a class creates an instance of itself inside itself. I can think of three reasons offhand (two already mentioned)
  • 1: Singletons
  • 2: Factory methods.
  • 3: Self-referential classes (eg for linked lists).
  • Mukul Anand
    Greenhorn

    Joined: Nov 28, 2012
    Posts: 29
    Okay.. thanks all for your replies
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 39067
        
      23
    You’re welcome
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: Creating objects in the same class