Originally posted by Arivazhagan Arutchelvam: Is it possible to extend a class which is having only a private constructor?
No, because the subclass needs access to at least one constructor of the superclass.
If so does it means the same to have a final class and a class with the private constructor?
Making a class final also makes it impossible to subclass, so this has the same effect in this regard as making all constructors of the superclass private.
Is there any difference between the Final Class and a Class with a private constructor in any other context? [ February 20, 2008: Message edited by: Arivazhagan Arutchelvam ]
If you use nested classes, it's possible to subclass a class with a final constructor using another class contained within the same top-level class. Private does not prevent this sort of access.
Another difference is that if you have a private constructor, it's always possible to add another non-private constructor as well, and then the class can be subclassed.
Most importantly, if you want to prevent a class from being subclassed, then "final" makes this fact very clear. Using a private constructor may have a similar effect, but it will confuse the reader trying to figure out what you're up to.
You can instantiate a class with private constructors by using Reflection. This will work unless SecurityManager disallows it.
SCJP 1.4, SCWCD 1.3, SCBCD 1.3
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18670
posted
0
Also you can instantiate a method with private constructors if the class provides a static factory method. Look at java.util.regex.Pattern for example. Of course this has nothing to do with the original question about subclassing and final.
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.
subject: Final Class and Class with private constructor