So in my little Java program I had declared all my variables in the main method, but I wanted to be able to modify them from anywhere inside the class, so I declared them in the class body instead. Now I am not able to modify them inside the main method anymore. Is the solution for this to declare the variables static? If I were to do so would I still be able to change those variables from inside the main method?
public class MainGUI
{
int num1= 1366, num2= 528, num3= 482, sum; // declare these static?
public static void main(String args[])
{
sum = num1 + num2+ num3; //compiler tells me "non-static varable cannot be refrenced from a static context"
}
}
you have to create an instance of your class in order to access non static variables from your static methods in java.
or make your instance variables static so that you can access them directly without any instance from your static methods .
though, by convention static variables from static methods should be accessed with classname.variablename
please refer to this link about better understanding of different types of variable access