I am in the process of learning Java and I don\'t understand the difference between Object Variables and Class Variable. All I know is that in order for it to be a Class Var
An object variable is state dependent on a specific instance of a class, whereas a class variable is globally accessible through the class itself. That might be a little fuzzy, so here are some examples:
class Muffin {
private static final int calories = 9320;
public String flavor;
public Muffin( String flavor ){
this.flavor = flavor;
}
}
In this class, calories
is a class variable. In any other piece of code, you can get the number of calories in any kind of muffin by calling Muffin.calories
. In this case, the final
keyword is also used to make the number of calories constant.
In the same class, we have an object variable, flavor
. This is dependent on the instance of the class, and is set in the constructor.
Muffin myMuffin = new Muffin( "blueberry" );
So now you can access this specific muffin's flavor by calling myMuffin.flavor
. Notice how we need to instantiate a Muffin
object before we can access its flavor
.
The above example is a bit of a stretch, since different types of muffins would have different calorie counts. They are useful for constants, but here's a case where the value of the static variable changes:
class Muffin {
private static int next_id = 1;
public int id;
public String flavor;
public Muffin( String flavor ){
this.flavor = flavor;
id = next_id++;
}
}
In the second example, we need to have a unique ID number for every muffin we create, so we can have a static variable that gets incremented every time a Muffin
is instantiated. The static
keyword makes the value of next_id
persist through every call to the constructor, so the id
will be different and continue to increase for every new muffin.