How can we check that how many times a java program has executed previously?

前端 未结 2 1416
南笙
南笙 2021-01-16 05:32
class Testing{

    static int count = 0;
    public Testing(){
        count++;
    }
    public static void main(String[] args){
        Testing[] testObjects= new         


        
相关标签:
2条回答
  • 2021-01-16 06:15

    Declaring count as static binds that variable not to a class instance, but to the class itself. Therefore, all objects share a single count variable. The way you have your code set up, where you increment count in each constructor call, keeps track of how many Testing objects have been created throughout the lifetime of this program. If you want to persist data, you'll need to look at the Preferences class. Essentially, at the end of your program you'd put the value into storage:

    myPreferences.put("ObjectsCreated", Testing.count);
    

    Then retireve it later with

    int previous = myPreferences.getInt("ObjectsCreated", 0);
    
    0 讨论(0)
  • 2021-01-16 06:21

    You have to persist the value of count, for example to a file.

    0 讨论(0)
提交回复
热议问题