Static and non static fields

前端 未结 6 892
有刺的猬
有刺的猬 2020-12-04 00:36

just to clarify I am thinking of this right, in java a static field is a variable/field which is used by a whole class, or can be used by all objects refering to that class?

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-04 01:01

    A static field, or static class variable within a class is accessible before an instance of that class is created unlike instance variables. Instance variables (non-static variables) within a class are created when an instance of that class is created at run-time. Hence, non-static variables cannot be accessed until an instance of that class is created. Whereas, static class members can be accessed before that class is created or instantiated.

    All instances of that class can access the same static variable. On the other hand, instance variables are individual/encapsulated to each instance of a class.

提交回复
热议问题