Instance Variable Vs Class Variable in Java

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

public class Date {
protected int year;
protected int month;
protected int day;
protected static final int MINYEAR = 1583;

public Date(int newMonth, int newDay, int newYear) {
// Initializes this Date with the parameter values
month = newMonth;
day = newDay;
year = newYear;
}

public int yearIs() {
// Returns the year value of this Date
return year;
}

public int monthIs() {
// Returns the month value of this Date
return month;
}

public int dayIs() {
// Returns the day value of this Date
return day;
}
}

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?