Srikanth Bandaru Srikanth Bandaru - 22 days ago 7
Java Question

Accessing Static variables

public class Bicycle {

private int cadence;
private int gear;
private int speed;
private int id;
private static int numberOfBicycles = 0;

public Bicycle(int startCadence, int startSpeed, int startGear){
gear = startGear;
cadence = startCadence;
speed = startSpeed;

id = ++numberOfBicycles;
}
// ...
}


I learned in my class that
Static variables should be accessed by calling with class name
. i.e.
ClassName.VariableName


But in the code above, how is this statement
id = ++numberOfBicycles;
compiled without errors, even though the variable
numberOfBicycles
is
static

Answer

Static variables are owned by class rather than by its individual instances (objects). Referring static variables outside the class is by ClassName.myStaticVariable but inside the class it is similar to other instance variables.

You can always use static variables in non-static methods but you cannot use non-static variables in static methods reason being when static methods are loaded other non-static instance variables are not created.

So your statement id = ++numberOfBicycles; is perfectly valid and will compile without errors.

Comments