difference between 'static int' and 'i

2020-07-27 02:55发布

in java where and when do we use 'static int' and how does it differ from 'int'

标签: java
7条回答
家丑人穷心不美
2楼-- · 2020-07-27 03:35

static means it is not instance specific. It belongs to the class. Usually it goes with final.

public static final int MAX = 10000;  // Defined in MyClass

// Somewhere else you could do
int max = MyClass.MAX;  // notice no instance of MyClass needed.

EDIT : It does not have to be final, non final variables are fine as long as one is careful.

查看更多
欢心
3楼-- · 2020-07-27 03:37

Well.

It's used when declare member variables, and static refers to whether or not you need an instance of the given class to access it.

Typically, static is used for constants, or "helper" functions or variables. If you have too many, and if you end up combining static and non-static variables in a class, it ends up being suggestive of bad design (not all the time, though).

If a variable is static, it's value is shared between all usages (i.e. between all instances of the object). That is, if you change it, all other accesses will see the change.

A non-static variable will have a unique value per instance (as it can only be accessed per instance).

查看更多
forever°为你锁心
4楼-- · 2020-07-27 03:42

static int, which can be accessed directly without using objects. int, which cannot be accessed directly without using objects.

查看更多
家丑人穷心不美
5楼-- · 2020-07-27 03:43

static int: One variable per application Can be accessed without object.

int: One variable per object Cannot be accessed without object.

查看更多
对你真心纯属浪费
6楼-- · 2020-07-27 03:46

Using 'int' in a class means an integer field exists on each instance of the class. Using 'static int' means an integer field exists on the class (and not on each instance of the class)

查看更多
Emotional °昔
7楼-- · 2020-07-27 03:47

The modifier static defines a variable as a class variable, meaning that there is exactly one of it only. Without it, a variable is an instantiable variable, so this variable exist per Object.

For example:

class Test {
  static int i;
  int j;
}

class Test 2 {
   public static void main(String args[])  {
     Test test1 = new Test();
     Test test2 = new Test();
     test1.i = 1;
     test1.j = 2;
     test2.i = 3;
     test2.j = 4;
     System.out.println("test1.i: "+test1.i);
     System.out.println("test1.j: "+test1.j);
     System.out.println("test2.i: "+test2.i);
     System.out.println("test2.j: "+test2.j);
   }
}

If you create 2 objects of the Test class, both objects will "share" the i variable. But each object will have its own j variable.

In the example above, the output will be

test1.i: 3
test1.j: 2
test2.i: 3
test2.j: 4

You can read more about it at The Java Tutorials - Variables

查看更多
登录 后发表回答