I'm writing a simple money tracker as a practice project. Here is a shortened version of my code:
public class MoneyTracker {
float salary1;
public void enterSalary1(float newValue){
salary1 = newValue;
}
public static void main(String[] args) {
MoneyTracker monthlySpend = new MoneyTracker();
monthlySpend.enterSalary1(1385.50f);
System.out.println(salary1);
}
}
This produces the error:
non-static variable salary1 cannot be referenced from a static context.
After reading some threads, I changed the variable to read static float salary1;
which fixed the issue.
However, I have another simple program which I built following the java tutorials on the Oracle website, it has a very similar set up and as far as I can tell, should result in the same error, but this compiles and runs with no problems. The code:
public class Bicycle{
//declare instance fields
int gear = 1;
int speed = 0;
int pedalRPM = 0;
//constructor classes
public void changePedalRPM(int newValue){
pedalRPM = newValue;
}
public void changeGear(int newValue){
gear = newValue;
}
public void speedUp(int increment){
speed = speed + increment;
}
public void applyBrake(int decrement){
speed = speed + decrement;
}
public void printStates(){
System.out.println("pedalRPM:" + pedalRPM + " speed:" + speed + " gear:" + gear);
}
public static void main(String[] args) {
Bicycle bike = new Bicycle();
bike.changeGear(2);
bike.changePedalRPM(85);
bike.speedUp(15);
bike.printStates();
bike.speedUp(5);
bike.printStates();
}
}
I realise there is a printStates
method here which is called from inside the main method, which is the only difference, but I have tried this with my money tracker and I still get the non-static variable error.
Is anyone able to explain to me why I get two different results from relatively similar programs? It seems weird that no tutorials would mention this if the main method must be static and this is where the variables are utilised.
Edit - allow me to clarify my thinking.
In my money tracker example, I'm using equivalent code in equivalent places as the bicycle. The bicycle code is straight from Oracle so it must be a valid way of doing things.
I have:
float salary1;
in the same place as
int gear = 1;
My constructor
public void enterSalary1(float newValue){
salary1 = newValue;
}
is in the same place as (for example)
public void changeGear(int newValue){
gear = newValue;
}
I then make a new instance of the class, inside the main method:
MoneyTracker monthlySpend = new MoneyTracker();
Which is the same as
Bicycle bike = new Bicycle();
My statements are then in the same place as in the bicycle program
monthlySpend.enterSalary1(1385.50f);
is equivalent to
bike.changeGear(2);
The Bicycle program compiles and the Money Tracker does not. I do understand the answers that say I can't call a non-static variable from a static method - but it appears that one of the programs allows me to, so where is the difference?
Thanks you for all of your answers!