• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

doubt in constructor access modifier...

 
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,
Can anybody please tell me... what is ruling for access modifiers of the constructor...
A constructor must have the same access modifier as it's class?
Please help me....
 
Ranch Hand
Posts: 537
Eclipse IDE Python Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A constructor can have any modifier. Its rules are same as using access modifiers for methods. there is no rule that the access modifier of the class and its constructor should be same. Class can have only public and default access modifiers while constructor can be protected public private and default.
 
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
No, the classes' and constructors' access modifiers share no connection.

Usually you would mark your constructor as public, so any class can build an instance of it.

The best example not to do this though is the Singleton pattern.
In a Singleton you mark the constructor as private, so nobody but your own class can instantiate it.

To provide an instance to other classes, you would create a public static function that builds the instance on demand.
This allows you to control instances and impose restrictions, in the case of the Singleton you would only allow one instance.
 
reply
    Bookmark Topic Watch Topic
  • New Topic