A field to count the amount instances of a class [duplicate]

时光怂恿深爱的人放手 提交于 2019-12-25 04:55:16

问题


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.


回答1:


This is because of the invalid use of ++ operator.

Your code can be corrected simply by correcting the line as below.

// count = count++; incorrect
count++; // correct
// count = count + 1; // correct

When you use count++, the count variable is incremented by 1; but the value returned from the operator is the previous value of count variable.

You can learn this by trying the below.

public class Test {
    public static void main(String[] args) {
        int count = 0;
        System.out.println(count++); // line 1
        System.out.println(count++);
    }
}

When you run above below is the results.

0
1

That is "line 1" prints only 0 since the return value of count++ is always the previous value.




回答2:


Use just:

count++;

Why? because:

count = count ++;

is similar to doing something like this:

temp = count ;  // temp is 0.
count = count +1;  // increment count
count = temp;   // assign temp (which is 0) to count.

Take a look at a similar post-increament question.




回答3:


The post increment operator implicitly uses a temp variable. so,

count = count ++;

is not equal to

count++;

in java.



来源:https://stackoverflow.com/questions/20453948/a-field-to-count-the-amount-instances-of-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!