Hello, I am very new to Java and was going through the Oracle tutorial. I got to the variables page and have got stuck on understanding the difference between static and non-static variables.
I am using the famous Bicycle object as an example. The class defines non static variables and from what the Java definition is of a non static variable, I was under the impression that this means no matter how many objects you create from this class, they will all have their own values even when the variable is manipulated in various objects.
Here is Java's definition:
Instance Variables (Non-Static Fields) Technically speaking, objects store their individual states in "non-static fields", that is, fields declared without the static keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words); the currentSpeed of one bicycle is independent from the currentSpeed of another.Instance Variables (Non-Static Fields) Technically speaking, objects store their individual states in "non-static fields", that is, fields declared without the static keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words); the currentSpeed of one bicycle is independent from the currentSpeed of another.
And the example code:
package Bicycle; public class Bicycle { int cadence = 0; int speed = 0; int gear = 1; void changeCadence(int newValue){ cadence = newValue; } void changeGear(int newValue){ gear = newValue; } void speedUp(int increment){ speed = speed + increment; } void applyBrakes(int decrement){ speed = speed - decrement; } void printStates(){ System.out.println("Cadence: "+cadence+" Speed: "+speed+" gear: "+gear); } }
package Bicycle; public class BicycleDemo { public static void main(String[] args){ Bicycle bike1 = new Bicycle(); Bicycle bike2 = new Bicycle(); bike1.changeCadence(50); bike1.speedUp(10); bike1.changeGear(2); bike1.printStates(); bike2.changeCadence(50); bike2.speedUp(2); bike2.changeGear(2); bike2.changeCadence(40); bike2.speedUp(10); bike2.changeGear(3); bike2.printStates(); } }
From what Java states about static variables, I thought the static modifier acted the same how the '&' in PHP in that it would create a reference. Java states that when declared it tells java that there is exactly 1 copy of the variable in existence. I thought this means if you change a value in one object, it would set the same value in the other object.
So, I added the static keyword to all variables when declared but I get the exact same result. Am I completely getting the wrong idea?
Please help!
Regards,
SS