...static declarations aren't allowed within an inner class...
Originally posted by John Cozens:
Mike
====
Thanks Mike. I reckon you and Pedro are both right - these are merely different solutions to achieving a Singleton. Yours is definitely more appropriate when you want to instantiate your Singleton up-front (say during initialisation while the user's looking at a dazzling splash screen ), while Pedro's is more appropriate when you want to use "lazy instantiation"...that means you want your Singleton built on a "Just in Time" basis, the first time that getInstance() is called, and not a moment sooner. That can be useful if say you've got 10 million potential Singleton Objects, of which you'll probably only ever need 50 during a typical program run, but you don't know which ones you'll need in advance.
SCJP 1.4, SCJD
Eben Hewitt. SCJP, SCWCD, SCJD, SCJWSD for JEE 5, TOGAF 8 Certified Architect, author of Java SOA Cookbook (O'Reilly, 2009) and contributor to 97 Things Every Software Architect Should Know
Originally posted by John Cozens:
Mike, OK but what if you have a variable within some other class of type Singleton (which you don't plan to instantiate by using Singleton.getInstance() for the next few days). Given that the static variable "instance" in Singleton is, well, static, won't it get initialised during class-loading? So if you use this form:
...then 'instance' will actually become an object of type Singleton as a result of class-loading, regardless of whether another class ever calls getInstance() on it or not? I'm not sure we're actually disagreeing on this, I'm just trying to be totally clear in my own mind.
SCJP 1.4, SCJD
'Of type Singleton' ?
So a subclass of Singleton?
How can you have a subclass if the default constructor is private?
So if you did have a million classes that used the above form of Singleton, I'd expect that you'd have constructed a million Objects on start-up, regardless of whether you ever called getInstance() on any of them during the course of the app. They'd just sit there, presumably consuming space on the heap.
SCJP 1.4, SCJD