Variable Scope in Java – Java中的变量范围

最后修改: 2019年 1月 22日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In Java, as in any programming language, each variable has a scope. This is the segment of the program where a variable can be used and is valid.

在Java中,如同在任何编程语言中,每个变量都有一个范围。这是程序中一个变量可以被使用并且有效的部分。

In this tutorial, we’ll introduce the available scopes in Java and discuss the differences between them.

在本教程中,我们将介绍Java中可用的作用域,并讨论它们之间的区别。

2. Class Scope

2.班级范围

Each variable declared inside of a class’s brackets ( {} ) with private access modifier but outside of any method, has class scope. As a result, these variables can be used everywhere in the class, but not outside of it:

在类的大括号({})内声明的每个变量都带有private访问修饰符,但在任何方法之外,都有类的范围。因此,这些变量可以在类的任何地方使用,但不能在类外使用

public class ClassScopeExample {
    private Integer amount = 0;
    public void exampleMethod() {
        amount++;
    }
    public void anotherExampleMethod() {
        Integer anotherAmount = amount + 4;
    }
}

We can see that ClassScopeExample has a class variable amount that can be accessed within the class’s methods.

我们可以看到ClassScopeExample有一个类变量amount,可以在该类的方法中访问。

If we don’t use private, it will be accessible from the entire package. Check access modifiers article for additional information.

如果我们不使用private,它将被整个包所访问。请查看access modifiers文章以了解更多信息。

3. Method Scope

3.方法范围

When a variable is declared inside a method, it has method scope and it will only be valid inside the same method:

当一个变量被声明在一个方法里面时,它就有了方法的范围,它只在同一个方法里面有效:

public class MethodScopeExample {
    public void methodA() {
        Integer area = 2;
    }
    public void methodB() {
        // compiler error, area cannot be resolved to a variable
        area = area + 2;
    }
}

In methodA, we created a method variable called area. For that reason, we can use area inside methodA, but we can’t use it anywhere else.

methodA中,我们创建了一个名为area的方法变量。由于这个原因,我们可以在methodA中使用area,但我们不能在其他地方使用它。

4. Loop Scope

4.循环范围

If we declare a variable inside a loop, it will have a loop scope and will only be available inside the loop:

如果我们在一个循环内声明一个变量,它将有一个循环范围,只在循环内可用:

public class LoopScopeExample {
    List<String> listOfNames = Arrays.asList("Joe", "Susan", "Pattrick");
    public void iterationOfNames() {
        String allNames = "";
        for (String name : listOfNames) {
            allNames = allNames + " " + name;
        }
        // compiler error, name cannot be resolved to a variable
        String lastNameUsed = name;
    }
}

We can see that method iterationOfNames has a method variable called name. This variable can be used only inside the loop and is not valid outside of it.

我们可以看到方法iterationOfNames有一个名为name的方法变量。这个变量只能在循环内使用,在循环外是无效的。

5. Bracket Scope

5.支架范围

We can define additional scopes anywhere using brackets ({}):

我们可以使用括号在任何地方定义额外的作用域{})。

public class BracketScopeExample {    
    public void mathOperationExample() {
        Integer sum = 0;
        {
            Integer number = 2;
            sum = sum + number;
        }
        // compiler error, number cannot be solved as a variable
        number++;
    }
}

The variable number is only valid within the brackets.

变量number只在括号内有效。

6. Scopes and Variable Shadowing

6.瞄准镜和可变阴影

Imagine that we have a class variable, and we want to declare a method variable with the same name:

想象一下,我们有一个类变量,我们想声明一个同名的方法变量。

public class NestedScopesExample {
    String title = "Baeldung";
    public void printTitle() {
        System.out.println(title);
        String title = "John Doe";
        System.out.println(title);
    }
}

The first time that we are printing title, it will print “Baeldung”. After that, declare a method variable with the same name and assign to it the value “John Doe“.

在我们第一次打印title时,它将打印 “Baeldung”。之后,声明一个同名的方法变量,并给它赋值为 “John Doe

The title method variable overrides the possibility to access to the class variable title again. That’s why the second time, it will print “John Doe.

title方法变量覆盖了再次访问class变量title的可能性。这就是为什么第二次会打印 “John Doe

Confusing, right? This is called variable shadowing and isn’t a good practice. It’s better to use the prefix this in order to access the title class variable, like this.title.

令人困惑,对吗?这被称为变量阴影,这不是一个好的做法。最好使用前缀this来访问title类变量,如this.title

7. Conclusion

7.结语

We learned the different scopes that exist in Java.

我们学习了Java中存在的不同作用域。

As always, the code is available on GitHub.

一如既往,代码可在GitHub上获得。