what is difference between declaring variable out of main method and inside main method?

前端 未结 6 580
我在风中等你
我在风中等你 2021-01-31 22:36

When I was reading book about Java , I saw one example written like this. And I am wondering can I declare variable in outside of main method ? What is difference between declar

6条回答
  •  面向向阳花
    2021-01-31 22:46

    What you refer to is the scope of a variable.

    Variables inside methods are only accessible inside this method, ie an_integer inside the main-method cannot be referenced outside the main method. Variables can even have narrower scopes, for exammple inside loops. The classic iterating variable of a for loop is only avaiable inside its loop, afterwards its gone.

    Variables outside methods are called fields. It depends on its access modifier where it can be seen. Private fields for example are only avaiable inside this class, public fields can be accessed from anywhere (other access modifiers are protected and none, which falls back on a default). Basically, you can use a field inside a class to access its value from every method inside this class, this, however, might be dangerous if multiple threads access the same instance of a class, but this is a whole other story.

    A field and a local variable may have the same name, which can lead to confusion. I would generally prefer not to do this, or, maybe better, always refer to fields with a this accessor. I am not entierly sure whether there is a preference of local variables versus fields of the same name, but I would guess local variables are of higher priority when determining which one was meant.

    Static fields now mean that this variable does not belong to an instance of a class, but to the class itself. Static fields (and methods) can be read (or invoked) without having to initialize the class first. An example could be a standardvalue of a class, or maybe a factorymethod (if its a method). Static fields may also come in handy for constants, together with the final modifier. A public final static field is pretty much a global constant.

提交回复
热议问题