全球变量申报问题

时间:2012-01-03 06:45:25

标签: java

我有全局变量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。由于我是编程新手,我不知道它是否有意义。

3 个答案:

答案 0 :(得分:1)

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!

答案 1 :(得分: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

希望这就是你的意思。他们。

答案 2 :(得分:-1)

如果我正确理解你的问题,你想在每次创建类的新对象时将temp重新初始化为0 - MyClass。

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

 public MyClass 
 {   
        temp = 0; 
 }

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

相关问题