This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Private Constructor in Java Class. Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Private Constructor in Java Class." Watch "Private Constructor in Java Class." New topic
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
    
    1

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
    
    4
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
    
    1

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!
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Private Constructor in Java Class.
 
Similar Threads
NullPointerException - could somebody explain why ?
Spring 3 @PathVariable problem with slash
Simple program but not getting class cast exception,why so?
Generics - Bounded Type Parameters - Query
java