• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Knute Snortum
  • Bear Bibeault
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Tim Holloway

Static Singleton

 
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class JustOne
{
private static JustOne currentInstance = null;
private JustOne() {}
static createJustOne()
{
if (currentInstance == null)
{ currentInstance = new JustOne();
}

}
return currentInstance ;
}

Why should the currentInstance be declared private static?anyway only instance of this class will be available in the JVM.

As currentInstance is static ,after calling createJustOne() once,nect time i can use the JustOne.currentInstance to get an instance of the class with out calling createJustOne();Is this right?
 
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Originally posted by raj joe:
Why should the currentInstance be declared private static?



Is your question about the private or the static?
1. private, to force you to use the access method.
2. static, so no more than one instance exists, since that is what is required.
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That code will not compile, you should change it to (for example):

static JustOne createJustOne()
 
author and iconoclast
Posts: 24203
43
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Originally posted by raj joe:

As currentInstance is static ,after calling createJustOne() once,nect time i can use the JustOne.currentInstance to get an instance of the class with out calling createJustOne();Is this right?



If it weren't private you could create as many instances as you wanted by calling createJustOne, setting currentInstance to null, calling createJustOne again, etc, etc.
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Additionally, having code that relies on other code already having already invoked createJustOne() is brittle design. It's better to always go through the method.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!