This question already has an answer here:
- post increment operator java 3 answers
I need to create a field to count the number of instances made by a class
public class Circle
{
private int diameter;
private int xPosition;
private int yPosition;
private String color;
private boolean isVisible;
private static int count = 0;
/**
* Create a new circle at default position with default color.
*/
public Circle()
{
diameter = 30;
xPosition = 20;
yPosition = 60;
color = "blue";
isVisible = false;
count = count++;
}
public void returnCount(){
System.out.println(count);
}
This is what Ive been playing with. I was hoping the count would increment by 1 each time a variable is created. However it just stays at 0.
Thanks for any help, Ciaran.
This is because of the invalid use of
++
operator.Your code can be corrected simply by correcting the line as below.
When you use
count++
, thecount
variable is incremented by 1; but the value returned from the operator is the previous value ofcount
variable.You can learn this by trying the below.
When you run above below is the results.
That is "line 1" prints only
0
since the return value ofcount++
is always the previous value.The post increment operator implicitly uses a temp variable. so,
is not equal to
in java.
Use just:
Why? because:
is similar to doing something like this:
Take a look at a similar post-increament question.