final just means it can't be overridden. A constructor can't be overridden, so what's the point of labelling it final? With most of the examples where a particular modifier isn't allowed in a particular place in Java, the explanation is simply that it wouldn't make much sense there.
Making a constructor private will (if it's the only constructor) prevent you from instantiating the class from outside the class. Which means it can only be instantiated from inside - e.g. in a static method. See, for example, the Singleton pattern.
saloni jhanwar wrote:but is there any sense to use any access modifiers with it ?
Well, the answer lies in Seetharaman Venkatasamy's post (previous to your last post). What if I want to 'stop' someone(external to my class) from creating objects? What if I want methods of 'my class' only should be able to create the objects?
I hope you get the point.
Edit : I was typing this when Matthew Brown replied, so its almost duplicate
Consider below scenario:
1) There are two threads which are calling getA method.
2) Thread 1 reaches line 10. a is null, so it reaches at line 11. Line 11 has not yet executed.
3) Thread 2 reaches line 10. a is null, so it reaches at line 11. Line 11 has not yet executed.
4) Thread 1 creates an object, assigns to 'a' and returns the object.
5) Thread 2 creates another object, assigns to 'a' and returns the object.
So, there are two possibilities to avoid this:
Personally, I prefer the first one for below reasons:
1) Instance is initialized during class loading itself.
2) There's no 'if' condition overhead during getInstance method.
3) We don't have to explicitly make it thread-safe.
I hope this helps.
Joined: Nov 01, 2011
Hi, thanks for your thread safe example.
By the way, this quoted code:
is equivalent to
So, if "this" Singleton instance is not created yet, will I get a null pointer exception?