I am getting output as 0 but it must be 5 as i think
Rakesh Bagaria
Greenhorn
Joined: Sep 06, 2009
Posts: 13
posted
0
//class with private constructor
class A
{
static int count =0;
//constructor
private A()
{
count=count+1;
}
//count function for object created
static void countfun(int n)
{
A ob[]=new A[n];
System.out.println("Number of Object created is "+count);
}
}
//main class
class PrivCons
{
public static void main(String args[])
{
A.countfun(5);
}
}
Lester Burnham
Rancher
Joined: Oct 14, 2008
Posts: 1337
posted
0
I don't see any instances of class A being created. The only thing that's being created is an array that can hold instances of class A; that does not cause those object to be created, though.
Welcome to javaRanch
Please use code tags while posting your Question.
it would be easier for other to read your post and also you will get a good response
Lester is right. If you create an array of objects, each element will remain null until explicitly set a value. Unless you use {} to set the values immediately that is:
First of all,
You have not created any instance of class A yet is the main reason and after all, you have made your default constructor as Private so it cant be accessible is different class that's why your code for count increment in the private default constructor would not work at all. Each and every time after creating your instance in this code will get count to be Zero as a result.
MCSA 2003 | Preparing For OCPJP/SCJP6
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.
subject: I am getting output as 0 but it must be 5 as i think