2

I have an object say A that loads some data from disk and it takes a bit long time to load. Many of other objects need its methods and data so I don't want neither any time I need it create a new one nor passing it through class constructor. Is there any way to create an instance of the class A only once at the beginning of the running project and all the other objects have access to the object A?

I apologize if my question is duplicated but I don't have any idea about what keywords relate to this question to find related questions.

user3070752
  • 694
  • 4
  • 23

2 Answers2

2

In that case you are dealing with the Singleton Design Pattern you should declare youre class like this:

public class SingleObject {

   //create an object of SingleObject
   private static SingleObject instance = new SingleObject();

   //make the constructor private so that this class cannot be
   //instantiated
   private SingleObject(){}

   //Get the only object available
   public static SingleObject getInstance(){
      return instance;
   }

   public void showMessage(){
      System.out.println("Hello World!");
   }
}

And then you can use it as intended.


In fact the approach here is to use static members like this:

public class Vehicle {

   private static String vehicleType;

    public static String getVehicleType(){
        return vehicleType;
    }

}

The static modifier allows us to access the variable vehicleType and the method getVehicleType() using the class name itself, as follows:

Vehicle.vehicleType
Vehicle.getVehicleType()

Take a look at Java static class Example for further information.

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
1

Sure. The design pattern is called a singleton. It could look like this:

public class Singleton {
    private static Singleton instance;
    private Singleton () {}

    /*
     * Returns the single object instance to every
     * caller. This is how you can access the singleton
     * object in your whole application
     */
    public static Singleton getInstance () {
        if (Singleton.instance == null) {
            Singleton.instance = new Singleton();
        }
        return Singleton.instance;
    }
}

All objects can use the singleton by calling Singleton.getInstance()

Ian2thedv
  • 2,691
  • 2
  • 26
  • 47
Thomas Uhrig
  • 30,811
  • 12
  • 60
  • 80
  • 3
    Note that that implementation of the singleton pattern isn't thread-safe - there are various better ones. Read Effective Java for details. – Jon Skeet Jul 20 '15 at 09:35