繁体   English   中英

全局变量声明问题

[英]Global variable declaration issue

我有全局变量private int temp=0; 在该类中,它是递增的(在某个阶段说是temp = 10)。再次加载该类时,temp仍然是10。但是我需要将其设置为0。我该怎么做?

码:

public class MyClass
{
private int temp = 0;

  public void method1() // while calling this method temp increments say temp =1;
  {
  temp++;
  }

  public void method2()
  {
  if(temp == 0)
  System.out.println("temp = "+temp):
  }
}

在此之后,假设temp = 10 ,并且在加载MyClass仍然temp=10 ,但是我再次需要temp=0 由于我是编程新手,所以我不知道它是否有意义。

除非声明为静态,否则temp 始终为0。

MyClass mc = new MyClass();
mc.method1() // 'temp' of mc object is now 1
MyClass mc2 = new MyClass();
mc2.method2() //'temp' of mc2 object is still 0!

我不确定加载类调用类等的含义

请注意, 该类的每个新实例将为您提供temp = 0并且如果您是在同一个实例中表示,请参见本示例,我添加了一个新方法method0()

public class MyClass
{
private int temp = 0;

  public void method0()
  {
    temp = 0;
  }

  public void method1()
  {
  temp++;
  }

  public void method2()
  {
  if(temp == 0)
  System.out.println("temp = "+temp):
  }
}

在这种情况下,

MyClass mc = new MyClass();
mc.method2();
mc.method1();
mc.method2();
mc.method0();
mc.method2();

会给你,

temp = 0
//Incremented value of temp
//condition if(temp==0) fails
//reset value of temp
temp = 0

希望这就是你的意思。

如果我正确理解了您的问题,则每次创建类的新对象-MyClass时都希望将temp重新初始化为0。

如果这是您想要的,请使用构造函数。 并在构造函数中将temp初始化为0。

 public MyClass 
 {   
        temp = 0; 
 }

这样,每次创建MyClass的新对象时,temp都将重新设置为0。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM