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
A static method can only access static data members and static methods of another class or same class but cannot access non-static methods and variables.
A static method can be called directly from the class, without having to create an instance of the class. A static method can only access static variables; it cannot access instance variables. Since the static method refers to the class, the syntax to call or refer to a static method is: class name. method name.
"Can a non-static method access a static variable or call a static method" is one of the frequently asked questions on the static modifier in Java, the answer is, Yes, a non-static method can access a static variable or call a static method in Java.
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.
Static variables are the shared variables. So you can access them using either the Classname.staticVariable or using an object of the class instance.staticVariable. In any case you will be referring to the single copy of the variable in memory, no matter how many objects you create.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With