• 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

prevent constructors from being instantiating

 
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
can anyone suggest which is the right answer in this question and why? And if there are any other ways to prevent instantiating of constructors???

6. In regard to constructors, how can you prevent a class from being instantiated?

A. Use the private declaration.
B. Use anonymous classes.
C. Employ overloading.
D. Use only static inner classes.
 
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If the constructor is private then nothing outside of the class can access it...(any private method/field is invisible except to the class in which it is defined).
 
Gurpreet Singh
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please explain, why does
class Test {
public static void main(String[] args) {
Test t = new Test();
}
private Test() {
System.out.println("Constructor says that he is here.");
}
}

complies but

class Test {
public static void main(String[] args) {
Test t = new Test();
}
private Test() {
System.out.println("Constructor says that he is here.");
}
}

class MoreTest {
void test() {
Test t = new Test();
}
}

does not??? Maybe because the Instantiation is within the class itself (in the class in which the constructor is declared). Am I right???
 
Richard Quist
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Exactly right. If it's private you can't access it UNLESS the access is made from the same class (as your first code example does).
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic