• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

private constructors

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have the constructor of my class,say A, marked private. Can I instantiate an object of type A outside the class? If not, is this equivalent to A marked private? Is there any way of instantiating an object Of A outside it?
 
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
1. no, you wouldn't be able to instantiate A outside of the class (that's not saying that you can't get an A instance out of the class, though)
2. what do you mean by "marking A private"?
3. no, there's no way to create an instance outside of A but you can get a reference to a new instance via an static method in class A:


hope that helps
 
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello Neha,
Always remember that a class in Java can have only one of two access modifiers. It can be either public or default.
When the constructor is declared as private, there is not way out to call 'new' operator for that class from outside of that class body.
As Cesar said, only way is to create a static method inside that class which returns a new instance of that class. Mind that it should be a static method so that from outside world anyone can directly call that method without creating an instance of that class(which will not be possible as the class constructor is itself a private one).
 
Neha Mittal
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you Ceser and Rajshekhar!
 
reply
    Bookmark Topic Watch Topic
  • New Topic