Java中静态和非静态变量之间的区别

变量为我们提供了程序可以操纵的命名存储。Java中的每个变量都有一个特定的类型,该类型确定变量的内存大小和布局。可以存储在该内存中的值的范围;以及可以应用于该变量的一组操作。

静态变量

静态变量也称为类变量,在类的对象之间通用,并且也可以使用类名来访问此变量。

非静态变量

非静态类的任何变量称为非静态变量或实例变量。

以下是静态变量和非静态变量之间的重要区别。

序号

静态的
非静态
1个
访问
A static variable can be accessed by static members as well as non-static member functions.
静态成员函数不能访问非静态变量。
2
分享中
A static variable acts as a global variable and is shared among all the objects of the class.
非静态变量特定于创建它们的实例对象。
3
内存分配
Static variables occupies less space and memory allocation happens once.
非静态变量可能会占用更多空间。内存分配可能在运行时发生。
4
关键词
A static variable is declared using static keyword.
普通变量不需要具有任何特殊关键字。

静态与非静态变量的示例

JavaTester.java

public class JavaTester {
   public int counter = 0;
   public static int staticCounter = 0;
   public JavaTester(){
      counter++;
      staticCounter++;
   }
   public static void main(String args[]) {
      JavaTester tester = new JavaTester();
      JavaTester tester1 = new JavaTester();
      JavaTester tester2 = new JavaTester();
      System.out.println("Counter: " + tester2.counter);
      System.out.println("Static Counter: " + tester2.staticCounter);
   }
}

输出结果

Counter: 1
Static Counter: 3