Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

constructors  RSS feed

 
Manisha Sharma
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can i define constructors in private section?
 
vijay kumarg
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is possible to have private constructors, which prevent outside code except the creator of the class can instantiate it.
 
Gregg Bolinger
Ranch Hand
Posts: 15304
6
Chrome IntelliJ IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by vijayk gopu:
It is possible to have private constructors, which prevent outside code except the creator of the class can instantiate it.


That's not entirely true. Using the Reflection API you can instantiate an object that contains a private constructor. So yes, it is possible to have an object with a private constructor, but that does not keep code outside said object from instantiating it.
 
vijay kumarg
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gregg, Thankyou. I got a chance to look into the reflection api.It's interesting.Could you please tell us the situations to takeup this reflection concept.Will it be used in webservices?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Reflection can be useful for different purposes.
To learn more about reflection see the tutorial: The Reflection API
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I usually figure using reflection that way is "cheating." The designer's intent with a private constructor is pretty clear. Using reflection to violate the design intent ... well you may just get what you deserve.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!