Let us answer it one by one. But before that let us understand what is static variable and what is non-static variable. The static variable is a variable that belongs to a Class and not to any specific instance of the class whereas on the other hand a non static variable belongs to a class instance.
So consider below example
class A{
static Object someStaticValue;
Object someNonStaticValue;
}
A.someStaticValue = new Object(); //allowed
A.someNonStaticValue = new Object() //not allowed as someNonStaticValue belongs to instance of A and will be different for each instance of A
A objectA = new A();
objectA.someNonStaticValue = new Object(); //allowed as this will update someNonStaticValue which is in scope of objectA
objectA.someStaticValue = new Object(); //allowed as it will simply update the value of variable in Class scope.
A objectB = new A();
objectB.someNonStaticValue = new Object(); //allowed
objectB.someStaticValue = new Object(); //allowed as it will simply update the value of variable in Class scope.
objectA.someNonStaticValue
is not equal to objectB.someNonStaticValue
as they belong to two different scope
whereas A.someStaticValue
, objectA.someStaticValue
,
objectB.someStaticValue
-> All are equal as they are updating the
variable in class scope.
Now coming to your questions:
Why can't you declare a static variable in a static or non-static method?
Any variable declared inside a method will have scope inside a method and hence can never belong to a class. Every time you will call that method a new instance will be used and hence will be different for each call and hence no purpose of making a variable static inside a method
When you make static variables, do you HAVE TO make them in the class?
Not possible in the methods?
Yes, because creating in methods will solve no purpose and will not be able to keep the definition of static as the values will change in different calls to that method.
Since I declared notNumber as non-static, I know I have to create an
object to access that variable. But why does it work in whatever()
without any creation of objects, but not in the static method main()?
Because in whatever() function, it is sure that you have created a new instance of the class using which you have called this function, calling a non-static variable inside a non-static variable is allowed. Also, in this case, its clear to JVM which instance scope to use for this variable. However, when it comes to static method, there is no guarantee that the instance of the class has been created or not and also of which class instance scope to be used for that non-static variable. Hence, calling non-static variable from a static method is not allowed.