23

When to use the getInstance() method in java and what is the meaning of getInstance(null)?

locationProvider = LocationProvider.getInstance(null); 

can anyone tell me the meaning of the above line?

Nandkumar Tekale
  • 16,024
  • 8
  • 58
  • 85
Roster
  • 1,764
  • 6
  • 17
  • 36
  • 4
    [This answer](http://stackoverflow.com/a/3169644/1830334) is better than the others here. – jds Mar 19 '15 at 15:52
  • Actually, the below answer is (arguably) a lot more clear/practical than the top answer linked in the previous comment: https://stackoverflow.com/questions/10477281/please-tell-me-when-to-use-getinstance-method-in-java#10477301 . – user3773048 Aug 31 '20 at 21:31

3 Answers3

38

Classes that use getInstance() methods and the like are of the singleton design pattern. Basically, there will only ever be one instance of that particular class, and you get it with getInstance().

In this case, LocationProvider will only ever have one instance, since it's device-specific. Instead of creating new instances of it, you can use the shared instance by using the getInstance() method. The singleton pattern is often used in Java when dealing with things like data managers and hardware interfaces, but it shouldn't be used for too much else, since it restricts you to a single instance.

Alexis King
  • 43,109
  • 15
  • 131
  • 205
4

Method getInstance() is called factory method. It is used for singleton class creation. That means only one instance of that class will be created and others will get reference of that class.

Bhavik Ambani
  • 6,557
  • 14
  • 55
  • 86
  • This is incorrect. For example, `Calendar.getInstance() == Calendar.getInstance()` is `false`. – jds Mar 19 '15 at 15:47
  • Calendar.getInstance() == Calendar.getInstance() return value depends on getInstance() implementation. If getInstance() returns the same object each time, above equality comparison would return true – phoenix Jul 24 '21 at 11:26
3

The following code will give you the latitude and longitude. getInstance() will give back the instance of that particular class.

    Criteria myCriteria = new Criteria();
    myCriteria.setCostAllowed(false);
    LocationProvider myLocationProvider = LocationProvider.getInstance(myCriteria);
    Location myLocation = myLocationProvider.getLocation(300);
    latitude  = myLocation.getQualifiedCoordinates().getLatitude();
    longitude = myLocation.getQualifiedCoordinates().getLongitude();
Rince Thomas
  • 4,158
  • 5
  • 25
  • 44