Instance Variable Vs Class Variable in Java

To explain the difference between Instance variables and Class variables, let’s start with an example:

As you can see above, the Date class demonstrates two kinds of variables: instance variables and class variables. The instance variable of the Date class are year, month, and day. Their values vary for each different instance of an object inside the Date class. Instance variables represent the attributes of an object.

MINYEAR is a class variable because it is defined to be static. The static modifier makes it so that the MINYEAR class variable It is associated directly with the Date class, instead of individual objects inside the Date class. Therefore, a single copy of a static variable is attributes to all the objects inside a class, not individual ones.

Also notice that the final modifier is added to MINYEAR, meaning that this variable is in its final form and cannot be modified or changed.

More Notes:

  • Constants are also known as static variables
  • To re-iterate, static variables like MINYEAR in the example above are used to attribute information that is common to an entire class.

What's Your Opinion?