什么是静态变量

时间:2015-02-26 14:13:06

标签: java static

我正在寻找静态变量的意思 我找到这个网站

http://java-questions.com/keywords-interview-questions.html

及其关于静态变量的声明 当我使用他的例子时,我发现了不同的结果

静态关键字可以与变量和方法一起使用,但不能与类一起使用。声明为静态的任何内容都与类有关,而与对象无关。

静态变量:类的Multiples对象共享静态变量的相同实例。考虑示例:

public class Counter{
 private static int count=0;
 private int nonStaticcount=0;
 public void incrementCounter(){
   count++;
   nonStaticcount++;
 }
 public int getCount(){
  return count;
 }
 public int getNonStaticcount(){
  return nonStaticcount;
 }

 public static void main(String args[]){

   Counter countObj1 = new Counter(); 
   Counter countObj2 = new Counter();
   countObj1.incrementCounter();
   countObj1.incrementCounter();
   System.out.println("Static count for Obj1: "+countObj1.getCount());
   System.out.println("NonStatic count for Obj1: "+countObj1.getNonStaticcount());
   System.out.println("Static count for Obj2: "+countObj2.getCount())
   System.out.println("NonStatic count for Obj2: "+countObj2.getNonStaticcount())
 }

输出

Static count for Obj1: 2
NonStatic count for Obj1: 1
Static count for Obj2: 2
NonStatic count for Obj2 :1

当我使用这个例子时我得到了

 Static count for Obj1: 2  
    NonStatic count for Obj1: 2 // instead of 1
    Static count for Obj2: 2
    NonStatic count for Obj2 :0 // instead of 1

任何人都可以告诉我静态变量是什么意思,示例声明如何在我的方法中使用它

谢谢

2 个答案:

答案 0 :(得分:3)

您得到了错误的结果,因为您正在递增countObj1两次:

Counter countObj1 = new Counter(); 
Counter countObj2 = new Counter();
countObj1.incrementCounter();
countObj1.incrementCounter();
//     !!!

将其替换为:

Counter countObj1 = new Counter(); 
Counter countObj2 = new Counter();
countObj1.incrementCounter();
countObj2.incrementCounter();

现在,你得到了正确的结果:

Static count for Obj1: 2    //Counter.count
NonStatic count for Obj1: 1 //obj1.nonStaticcount
Static count for Obj2: 2    //Counter.count (the same as in the first line)
NonStatic count for Obj2 :1 //obj2.nonStaticcount

答案 1 :(得分:1)

您在同一个对象上调用incrementCounter()两次:

   countObj1.incrementCounter();
   countObj1.incrementCounter();

相反,你应该这样做:

   countObj1.incrementCounter();
   countObj2.incrementCounter();