Java – static variables and methods

I encountered a class set like this:

public class MyClass {

  private static boolean started = false;

  private MyClass(){
  }

  public static void doSomething(){
    if(started){
      return;
    }
    started = true;
    //code below that is only supposed to run
    //run if not started
  }
}

My understanding of static methods is that you should not use class variables in them unless they are constants and do not change Instead, you should use parameters My question is, why by executing MyClass Dosomething() does not break when called multiple times In my opinion, it should not work, but it does It passes the if statement only once

So anyone can explain to me why it doesn't break?

Solution

Both the method dosomething () and the start variable are static, so there is only one copy of the variable that can be accessed from dosomething () When dosomething () is called for the first time, start is false, so it is set to true, and then... Well, something The second and subsequent times it is called are true, so it returns without doing anything

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>