Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Rakesh Bagaria
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
//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
Posts: 1337
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1051
Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Rob Spoor
Sheriff
Pie
Posts: 20531
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
Vishal Kashyap
Ranch Hand
Posts: 73
BSD C++ Fedora
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic