Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Access Modifiers & Constructors

 
Neil S Staish
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I thought I understood how access modifiers work with and affect classes in and outside packages, until I found out that constructors too could have access modifiers. I mean what happens if a "protected" class has a "private" constructor? Are there any rules? The study guide by Roberts has nothing about this.
 
Maulin Vasavada
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Neil,
here is the deal,
1. a class can't be protected/private
2. if the constructor of any class is private then it essentially means that we can't instantiate an object of that class if that was the only constructor for that class. you might wonder why we would make constructor private? well, if you do research on "Singletone" object then you will know why and when we would need private constructors...
also, sometimes we have say three constructors and we have only two out of them which really needs to get exposed to the public (who will use the class). the third constructor is only there for our easy code maintenance (to share the code that will otherwise get duplicated in the other two constructor) you know...
hope this helps..
again to summarize,
1. a top level class can't be private/protected
2. only methods (which includes constructors) can have all the four access specifiers
regards
maulin.
 
Garrett Smith
Ranch Hand
Posts: 401
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's more common than you think to have a private constructor.
Math is one example of a class with a private constructor.
The result is what you'd expect --you can't access it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic