What exactly is the difference between a final class and having a class constructor as private.
I know both can’t be subclassed(correct me if i am wrong). Is their any difference?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
A final class cannot be extended. It prevents this
This is useful for things like String – you wouldn’t want someone to be able to overwrite the logic of String, one of the most commonly used Objects, and be able to, oh I don’t know, add networking and send all the strings back you use. It’s possible to do if you can extend String.
A private constructor cannot be called outside the class.
Often this ends up working like this: (java.lang.Math is a good example)
Or it ends up working like this // Integer does this actually
When you extend a class, your constructor by default attempts to call the default (no argument) constructor. If that is private, then you must explicitly call a non-private constructor when you extend it. If you have no non-private constructors to call you won’t be able to extend it. Thanks for comments for pointing this out. 🙂