Reputation: 2392
According to Java Concurrency in Practice book:
Informally, an object's state is its data, stored in state variables such as instance or static fields.
As far as I understand from Java concepts or in general, state / instance variables define the object state. As far as I know, the static fields belong to class variables. In what case does static fields define object's state?
Upvotes: 0
Views: 2275
Reputation: 2535
It sounds a bit ambiguous to me - one could probably argue that static variables are inherently object state that is the same for all objects of a given type.
Personally, however I don't think that static variables constitute object state. This quote from the Oracle Java tutorial seems to support my understanding.
Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.
For example, suppose you want to create a number of Bicycle objects and assign each a serial number, beginning with 1 for the first object. This ID number is unique to each object and is therefore an instance variable. At the same time, you need a field to keep track of how many Bicycle objects have been created so that you know what ID to assign to the next one. Such a field is not related to any individual object, but to the class as a whole.
With that said, static variables can keep track of the status of the overall application state, which is what another question based on the same books speaks to: Object's state in public static fields
Upvotes: 2
Reputation: 2392
From Wiki
In object-oriented programming, there is also the concept of a static member variable, which is a "class variable" of a statically defined class, i.e., a member variable of a given class which is shared across all instances (objects), and is accessible as a member variable of these objects
Since static variable in class is shared across all the instances (objects) of class, it plays a role directly or indirectly in state of that object.
Upvotes: 0