You cannot refer to non-static variables in static methods without creating objects. The variables number1, number2 and sum
in your code are non-static and you are directly referring to them in main()
which is declared as static.
If your program does not require multiple objects or if the value of number1, number2 and sum
are going to be same for all the objects, you could simply solve the problem by making those variables static.
static int number1, number2, sum;
What does static mean?
- static variables are class variables which means there is only one copy of that variable for all the objects of the class.
If you would like to have multiple objects of the class Account
and different copies of the variable for each object, then you could do the following.
Step1 : Keep the variables as it is. Do not make them static.
Step2 : Create an object in main()
while referring to the non-static variables.
Inside main()
:
Account obj=new Account();
Account obj1=new Account();
//objects created and each object has a separate copy of the variables
obj.number1=....;
obj.number2=………;
obj1.number1=……;
//so on.
Summing up:
- You need to create objects while referring to non-static fields in static methods. Because static methods are class methods and does not belong to a particular object of the class. You could also make the variables static if it isn't a problem.