File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Instantiating Class with private constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Instantiating Class with private constructor " Watch "Instantiating Class with private constructor " New topic
Author

Instantiating Class with private constructor

Hai Yee
Greenhorn

Joined: Jan 03, 2001
Posts: 11
Hi,
For a class with 1 private constructor and 2 public constructors, a mock exam question stated that you can only instantiate the class in 2 ways only because of the private constructor. This is true except in the case demonstrated below. So for the purpose of the exam, what should it be? 2 or 3 ways?
Thanks,
-Hai
public class testJava
{
private testJava()
{
System.out.println("private testJava()");
}
public testJava(int i)
{
System.out.println("public testJava(int)");
}
public testJava(int i, int j)
{
System.out.println("public testJava(int, int)");
}

public static void main(String a[])
{
new testJava();
new testJava(1);
new testJava(1,1);
}
}

Hai Yee<br />SCJP,SCWCD,SCJD
Sean Casey
Ranch Hand

Joined: Dec 16, 2000
Posts: 625
This works fine within the same class, but you can't instantiate an object with a call to a private constructor outside of the class.
sunilkumar ssuparasmul
Ranch Hand

Joined: Dec 13, 2000
Posts: 142
Hai Yee,
what do we mean by private is u cannot access it outside the class, in this case since u r accesing within the same class no problem bcos all private public and protected are same within a class
now look at the following
class Test12{
private Test12(){}
}

public class Test4 {
public static void main(String[] args){
Test12 t = new Test12();
}
}
this will not compile and try removing private and then check

HTH
sunil.s


"Winners don't do different things<br /> They do things differently"
Hai Yee
Greenhorn

Joined: Jan 03, 2001
Posts: 11
sunil.s,
I get your point. But my point is that if you were only given a class with 1 private and 2 public constructors and ask how many ways can you instantiated this object, what would your answer be? 2 or 3? Being that if you instantiated from within the class, it's 3, but outside, it's 2.
Thanks,
-Hai
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Instantiating Class with private constructor