Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Instantiating Class with private constructor

 
Hai Yee
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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);
}
}
 
Sean Casey
Ranch Hand
Posts: 625
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Hai Yee
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic