I've written this test code:
class MyProgram
{
int count = 0;
public static void main(String[] args)
{
System.out.println(count);
}
}
But it gives the following error:
Main.java:6: error: non-static variable count cannot be referenced from a static context
System.out.println(count);
^
How do I get my methods to recognize my class variables?
You must understand the difference between a class and an instance of that class. If you see a car on the street, you know immediately that it's a car even if you can't see which model or type. This is because you compare what you see with the class "car". The class contains which is similar to all cars. Think of it as a template or an idea.
At the same time, the car you see is an instance of the class "car" since it has all the properties which you expect: There is someone driving it, it has an engine, wheels.
So the class says "all cars have a color" and the instance says "this specific car is red".
In the OO world, you define the class and inside the class, you define a field of type
Color
. When the class is instantiated (when you create a specific instance), memory is reserved for the color and you can give this specific instance a color. Since these attributes are specific, they are non-static.Static fields and methods are shared with all instances. They are for values which are specific to the class and not a specific instance. For methods, this usually are global helper methods (like
Integer.parseInt()
). For fields, it's usually constants (like car types, i.e. something where you have a limited set which doesn't change often).To solve your problem, you need to instantiate an instance (create an object) of your class so the runtime can reserve memory for the instance (otherwise, different instances would overwrite each other which you don't want).
In your case, try this code as a starting block:
The new
main()
method creates an instance of the class it contains (sounds strange but sincemain()
is created with the class instead of with the instance, it can do this) and then calls an instance method (run()
).The very basic thing is static variables or static methods are at class level. Class level variables or methods gets loaded prior to instance level methods or variables.And obviously the thing which is not loaded can not be used. So java compiler not letting the things to be handled at run time resolves at compile time. That's why it is giving you error non-static things can not be referred from static context. You just need to read about Class Level Scope, Instance Level Scope and Local Scope.
I will try to explain the static thing to you. First of all static variables do not belong to any particular instance of the class. They are recognized with the name of the class. Static methods again do not belong again to any particular instance. They can access only static variables. Imagine you call MyClass.myMethod() and myMethod is a static method. If you use non-static variables inside the method, how the hell on earth would it know which variables to use? That's why you can use from static methods only static variables. I repeat again they do NOT belong to any particular instance.
The
static
keyword modifies the lifecycle of a method or variable within a class. Astatic
method or variable is created at the time a class is loaded. A method or variable that is not declared asstatic
is created only when the class is instantiated as an object for example by using thenew
operator.The lifecycle of a class, in broad terms, is:
new
operator using the class to make an instance of the class as an actual object and then when done with the objectIn order to have an initial entry point for an application, Java has adopted the convention that the Java program must have a class that contains a method with an agreed upon or special name. This special method is called
main()
. Since the method must exist whether the class containing the main method has been instantiated or not, themain()
method must be declared with thestatic
modifier so that as soon as the class is loaded, themain()
method is available.The result is that when you start your Java application by a command line such as
java helloworld
a series of actions happen. First of all a Java Virtual Machine is started up and initialized. Next the helloworld.class file containing the compiled Java code is loaded into the Java Virtual Machine. Then the Java Virtual Machine looks for a method in thehelloworld
class that is calledmain(String [] args)
. this method must bestatic
so that it will exist even though the class has not actually been instantiated as an object. The Java Virtual Machine does not create an instance of the class by creating an object from the class. It just loads the class and starts execution at themain()
method.So you need to create an instance of your class as an object and then you can access the methods and variables of the class that have not been declared with the
static
modifier. Once your Java program has started with themain()
function you can then use any variables or methods that have the modifier ofstatic
since they exist as part of the class being loaded.However, those variables and methods of the class which are outside of the
main()
method which do not have thestatic
modifier can not be used until an instance of the class has been created as an object within themain()
method. After creating the object you can then use the variables and methods of the object. An attempt to use the variables and methods of the class which do not have thestatic
modifier without going through an object of the class is caught by the Java compiler at compile time and flagged as an error.This is bit diff to explain about static key word for all beginners.
You wil get to know it clearly when you work more with Classes and Objects.
|*| Static : Static items can be called with Class Name
If you observe in codes, Some functions are directly called with Class names like
This is because NamFnc and println wil be declared using key word static before them.
|*| Non Static :Non Static items can be called with Class Variable
If its not static, you need a variable of the class,
put dot after the class variable and
then call function.
Below code explains you neatly
|*| Static and non Static function in class :
|*| Static and non Static Class inside a Class :
Now you can add/use instances with in the method