posted 23 years ago
-----------------------------------------------------------------
You can make a constructor private if you do not want anyone to instantiate the class. A perfect example of this is the Math class. It has a private constructor, so no little "Maths" are going to be created. And, of course, all of it's methods are static, which means that you don't need a "math" instance to use the methods.
You can make a constructor friendly (no modifier) if you want only your stuff to be able to make instances of it. Classes in your package have no problem but you don't have to worry about what someone in some other package / application is going to do with your class. This is especially important if you have static variables where you need to have total control over the contents of the static variable. Imagine someone is in your application, minimizes it and starts another application that messes with your variables!!! Big problem.
You would use the protected modifier for similar reasons as the friendly use, but you are confident that if the other class is outside your package but extending your class, that they will treat your stuff properly or that there is nothing that they could damage.
Of course public is the best if you are trying to create a class that will be part of a library to be used across many applications / packages.
Not part of your question but a note about return types:
If you put a return type on a constructor you turn it into just another regular method, therefore it will not get called automatically, however you could explicitly call it from the code. This would be terribly confusing to all the rest of us poor programmers that have to read the code, so please don't make methods with the same name as the class unless it is a constructor (ie has no return type)!!
[This message has been edited by Cindy Glass (edited November 27, 2000).]
"JavaRanch, where the deer and the Certified play" - David O'Meara