public class Bicycle {
private int cadence;
private int gear;
private int speed;
private int id;
private static int numberOfBicycles = 0;
p
From within the class the Bicycle
qualifier is optional on static variables, just like the this
qualifier is optional on instance variables
Non static methods can access static members of a class because only a single copy of the static variable exists unlike instance variables which are only created once a new object of that type has been created.
I recommend you have another class to test,like BicycleTest which will have the main class and then create maybe 4Bicycle objects and using 2getters in the Bicycle class retrieve the numberofBicycles and ID everytime you create an object maybe that will give you a picture of what is happening.
public int getID(){
return numberOfBicycles;
}
public static int getNOB(){
return numberOfBicycles;
}
In the Bicycle class
Bicycle bc = new Bicycle(30, 90, 1);
System.out.println(Bicycle.getNOB());
System.out.println(bc.getID());
Bicycle bc2 = new Bicycle(30,90, 1);
System.out.println(Bicycle.getNOB());
System.out.println(bc2.getID());
Bicycle bc3 = new Bicycle(30,90, 1);
System.out.println(Bicycle.getNOB());
System.out.println(bc3.getID());
Bicycle bc4 = new Bicycle(30,90, 1);
System.out.println(Bicycle.getNOB());
System.out.println(bc4.getID());
In the main class of BicycleTest worked just fine for me
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.
you didn’t write Bicycle.numberOfBicycles. It isn’t necessary because we are already in that class so the compiler can infer it.
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.