Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create only one object for a class and reuse same object

Tags:

java

I want to create only one object of an class and reuse the same object over and over again. Is there any efficient way to do this.

How can I do this?

like image 816
Ajay Gopal Shrestha Avatar asked Jan 03 '13 08:01

Ajay Gopal Shrestha


People also ask

Can only one object be created in a class?

In object-oriented programming, a singleton class is a class that can have only one object (an instance of the class) at a time. After the first time, if we try to instantiate the Singleton class, the new variable also points to the first instance created.

Can you reuse an object in Java?

A feature of Java that makes it an extremely useful language is the ability to reuse objects.

Can we create more than one object for the same class?

No, it's fine. Just create an array (or List ) of Player and extract the code of Player creation in a separate method.

Can we create class object in the same class?

In java you cannot create a method outside of a class. All methods must be encapsulated within a class. Therefore the main method as an entry point to the program must be within a class. When you run this program the main method will be run once and will execute the code inside it.


2 Answers

public final class MySingleton {
    private static volatile MySingleton instance;

    private MySingleton() {
        // TODO: Initialize
        // ...
    }

    /**
      * Get the only instance of this class.
      *
      * @return the single instance.
      */
    public static MySingleton getInstance() {
        if (instance == null) {
            synchronized (MySingleton.class) {
                if (instance == null) {
                    instance = new MySingleton();
                }
            }
        }
        return instance;
    }
}
like image 146
Steve Avatar answered Oct 21 '22 05:10

Steve


This is generally implemented with the Singleton pattern but the situations where it is actually required are quite rare and this is not an innocuous decision.

You should consider alternative solutions before making a decision.

This other post about why static variables can be evil is also an interesting read (a singleton is a static variable).

like image 23
assylias Avatar answered Oct 21 '22 06:10

assylias