• Post Reply Bookmark Topic Watch Topic
  • New Topic

Using private methods in Constructors  RSS feed

 
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys. I'm in doubts is it a good practice to set private methods in Constructor or not. Could you please have a look on my Class on the matter?

Thanks!

 
Bartender
Posts: 3185
34
Google App Engine Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Private Constructors are used if you want to control the instantiation of the class. For example you want to have only one instance of that class through out your application (Singleton Pattern) you can make use of a private constructor and provide a method to access the instance. Like-

I dont think using private constructors can be classified as a good/bad practice. But they are handy during some implementations (like the one explained above).

Regarding the code posted- What is that you are looking for? The constructor you have declared has default scope. Try creating an instance of this class from another package.


Sorry for getting this wrong. When I saw private and constructor- I thought it was about private constructor. Didnt quite read the clear subject.
 
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
He is not asking about private constructors but about using private methods in constructors.

I don't see the problem why you shouldn't use private methods in constructors. In a matter of fact quite the opposite is true. you should not use visible (meaning public, protected or default) methods in your constructors. Or if you must be very careful. The point is that if sub-classes override that method that method will be called before it's instance variables are initialized.
 
You Gin
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys, that was useful - I read something I didn't know about.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!