| Author |
Private Constructor in Java Class.
|
Ivan Franko
Ranch Hand
Joined: May 30, 2011
Posts: 44
|
|
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
Joined: Feb 19, 2008
Posts: 2896
|
|
Doesn't really make sense, See Rob and Campbell reply
|
[LEARNING bLOG] | [Freelance Web Designer] | [and "Rohan" is part of my surname]
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
|
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.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
lokesh sree
Ranch Hand
Joined: Oct 27, 2009
Posts: 89
|
|
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?
|
Lokesh
( SCBCD 5, CCENT, SCJP 5 )
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32694
|
|
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
Joined: Feb 19, 2008
Posts: 2896
|
|
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!
|
 |
 |
|
|
subject: Private Constructor in Java Class.
|
|
|