Its said that non-static variables cannot be used in a static method.But public static void main does.How is that?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
**Here you can see table that clear the access of static and non-static data members in static and non-static methods. **
The main method does not have access to non-static members either.
This is because by default when you call a method or variable it is really accessing the
this.method()
or this.variable. But in the main() method or any other static method(), no "this" objects has yet been created.In this sense, the static method is not a part of the object instance of the class that contains it. This is the idea behind utility classes.
To call any non-static method or variable in a static context, you need to first construct the object with a constructor or a factory like your would anywhere outside of the class.
More depth:
Basically it's a flaw in the design of Java IMO which allows static members (methods and fields) to be referenced as if they were instance members. This can be very confusing in code like this:
That looks like it's sending the new thread to sleep, but it actually compiles down into code like this:
because
sleep
is a static method which only ever makes the current thread sleep.Indeed, the variable isn't even checked for non-nullity (any more; it used to be, I believe):
Some IDEs can be configured to issue a warning or error for code like this - you shouldn't do it, as it hurts readability. (This is one of the flaws which was corrected by C#...)
You can create non-static references in static methods like :
Same thing we do in case of
public static void main(String[] args)
methodNo, it doesn't.
but
or if you instantiate
A
Also
will work, since
a
is a local variable here, and not an instance variable. A method local variable is always reachable during the execution of the method, regardless of if the method isstatic
or not.Yes, the main method may access non-static variables, but only indirectly through actual instances.
Example:
What people mean when they say "non-static variables cannot be used in a static method" is that non-static members of the same class can't be directly accessed (as shown in Keppils answer for instance).
Related question:
Update:
When talking about non-static variables one implicitly means member variables. (Since local variables can't possible have a static modifier anyway.)
In the code
you're declaring a local variable (which typically is not referred to as non-static even though it doesn't have a static modifier).