Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / March 2004

Tip: Looking for answers? Try searching our database.

Constructors and modifiers

Thread view: 
Simon Higgs - 06 Mar 2004 20:07 GMT
Why is it possible to use public,protected,private and no (package) in
constructors. Surely the access is defined in the class declaration?

TIA, Simon.
Christophe Vanfleteren - 06 Mar 2004 21:03 GMT
> Why is it possible to use public,protected,private and no (package) in
> constructors. Surely the access is defined in the class declaration?
>
> TIA, Simon.

Because sometimes you need those options:

Suppose you want to have a class that everyone can use (a public class).
But, there's one thing: only one instance should ever be created (aka
singleton).

Now, if the constructors were public, anyone would be able to create any
number of instances, so you wouldn't be able to enfore the single instance
rule.

Now consider the following case:

public final class Singleton {
       
       private static Signleton instance = new Singleton;

       private Singleton() {
       //create object
       }

       public static Singleton getInstance() {
               return instance;
       }
}

By making the constructor private, we are now able to enfore that only one
instance of this class is created.

Signature

Kind regards,
Christophe Vanfleteren



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.