Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt in constructor access modifier...

 
Erum Momin
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • 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....
 
Nitish Bangera
Ranch Hand
Posts: 537
Eclipse IDE Java Python
  • Mark post as helpful
  • send pies
  • 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.
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic