Understanding Java: The Non-Access Modifier: Static
Author: Bryce Marshall - Student Blog Series
If you are wondering why you,
“can not make static reference to non-static [fill in the blank]”?
The Java language utilizes what are called modifiers, namely access and non-access types. These modifiers are keywords that allow us to modify our classes by fine-tuning the accessibility of its members. The five members of a class are variables (states), methods (behaviors), constructors, blocks, and inner classes.
The static keyword in Java is a non-access modifier. The static modifier makes a member (variables or methods) of a class independent of the objects of the class and is used when we are defining properties that are common to all objects in the class. Static variables are shared among all objects/instances within the class and can be accessed without reference to any object/instances. Static methods can only use static variables and call static methods.
Briefly, objects have a state (variables) and behavior (methods), and classes are the blueprints representing the properties or characteristics of the object. Objects and instances are very similar, and here is an example to illustrate the difference. Pretend that you have a basket of 6 oranges, and a class named Orange that will represent the real oranges in your basket. This class Orange, has the member variables size, shape, and color to represent characteristics of the object, an orange.
The object is an orange, and an instance represents each individual instance of an orange, such as orange1, orange2, etc. In other words, an instance is a copy or reference to the object itself at the particular time that it is instantiated. Objects are the definitions (states and behaviors), while instances are the physical things. You must define an orange before you can make copies of it.
The moral of the story is that a non-static member can not be referred to from a static method, and a static method can not access a non-static method or variable.
Interested in changing careers and becoming a software developer? Learn more about Promineo Tech's programs and how we help students make this transition through affordable, low-risk technology education: https://promineotech.com/coding-for-adults