静态变量和方法 [英] Static variables and methods

查看:44
本文介绍了静态变量和方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个这样设置的类:

I ran across a class that was set up 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
  }
}

我对静态方法的理解是你不应该在它们中使用类变量,除非它们是常量,并且不会改变.相反,您应该使用参数.我的问题是为什么通过执行 MyClass.doSomething() 多次调用这不会中断.在我看来它不应该工作,但确实如此.它只会通过一次 if 语句.

My understanding with static methods is that you should not use class variables in them unless they are constant, and do not change. Instead you should use parameters. My question is why is this not breaking when called multiple times by doing MyClass.doSomething(). It seems to me like it should not work but does. It will only go pass the if statement once.

那么谁能向我解释为什么这不会中断?

So could anyone explain to me why this does not break?

推荐答案

方法 doSomething() 和变量 started 都是静态的,所以只有一个副本变量,它可以从 doSomething() 访问.第一次 doSomething() 被调用时,started 是假的,所以它把 started 设置为真,然后......好吧,一些东西.第二次和后续调用时,started 为真,因此它什么都不做就返回.

The method doSomething() and the variable started are both static, so there is only one copy of the variable and it is accessible from doSomething(). The first time doSomething() is called, started is false, so it sets started to true and then does... well, something. The second and subsequent times it's called, started is true, so it returns without doing anything.

这篇关于静态变量和方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆