简体   繁体   中英

Scope of a variable declared in a method

Is a variable inside the main, a public variable?

    public static void main(String[] args) {
  .........

    for(int i=0;i<threads.length;i++)
        try {
            threads[i].join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    long time=0; 
    ....
    }

i and time are they both public variables?

Of course if my reasoning is correct, also any variable belonging to a public method should be considered public. Am I right?

Variables i and time are local only to the function. They are not visible outside. Only class member variables are accessible outside (subject to their access modifier).

The distinction has been covered in considerably greater detail already in SO here .

No. The variables 'i' and 'time' are declared inside the main method, so their scopes are local and limited to the main method only. You cannot use them outside the method.

They are not considered public. They are local variables. They do not have any visibility outside of that method (let alone that class).

No. If the variable is inside of a method -- even the main method -- it is a local variable and its scope is only within that method.

public class MyClass {
    public int x; // this is a public variable

    public void doSomething() { // this is a public method
        int y = 9; // this is a local variable
    }

    public int getX() {
        return x; // we can do this
    }

    public int getY() {
        return y; // we CANNOT do this because y is not public and is only 
                  // defined within the doSomething() method
    }
}

As others have said, the two variables can be used only in main. But i's scope is even more limited -- because it is declared in the for loop, it can be used only in the for loop.

Local variables are never public, irrespective of what method (or constructor) they may reside in. The scope of a local var is at most the whole method body.

The notions "public", "private" and similar do not apply to local variables, but to instance or class variables. The key difference is that local variables reside on the stack and thus their scope is automatically limited to the lifetime of a stack frame. They don't need any access rules. The access types "private", "default", etc. denote restrictions that need to be specifically imposed as they are not "natural". They can also be broken by reflection, unlike the scope of local vars.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM