aspose file tools*
The moose likes Beginning Java and the fly likes I am getting output as 0 but it must be 5 as i think Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "I am getting output as 0 but it must be 5 as i think" Watch "I am getting output as 0 but it must be 5 as i think" New topic
Author

I am getting output as 0 but it must be 5 as i think

Rakesh Bagaria
Greenhorn

Joined: Sep 06, 2009
Posts: 14
//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
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.
Shanky Sohar
Ranch Hand

Joined: Mar 17, 2010
Posts: 1051

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


SCJP6.0,My blog Ranchers from Delhi
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19693
    
  20

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:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Vishal Kashyap
Ranch Hand

Joined: Aug 07, 2010
Posts: 73

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://aspose.com/file-tools
 
subject: I am getting output as 0 but it must be 5 as i think