• Post Reply Bookmark Topic Watch Topic
  • New Topic

Private Constructor in Java Class.  RSS feed

 
Ivan Franko
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I investigate source code one project I found class, something like this:



My question:

Why role this peace of code:

?
 
Sagar Rohankar
Ranch Hand
Posts: 2907
1
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Doesn't really make sense, See Rob and Campbell reply
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But because another constructor is created manually (that takes two Strings), no default constructor will be created automatically. Therefore there is no need to "get rid of it" by creating a final one.
 
lokesh sree
Ranch Hand
Posts: 100
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since an overloaded constructor is written in the class, the default constructor also had to be provided.
But the author did not want the fields to be left uninitialized and hence made the constructor private and inaccessible to other classes.

But, I believe the lines
are not required inside the private default constructor and can be removed. Is that correct?
 
Campbell Ritchie
Marshal
Posts: 56562
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's not a default constructor; that would have package-private access.
I think that private constructor is a mistake. The reason the two fields are initialised is because they are final and the compiler error said they must be initialised.
 
Sagar Rohankar
Ranch Hand
Posts: 2907
1
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob Spoor wrote:But because another constructor is created manually (that takes two Strings), no default constructor will be created automatically. Therefore there is no need to "get rid of it" by creating a final one.

My bad, I somehow missed that simple thing. Thanks Rob!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!