Java 局部变量隐藏字段是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29832466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 08:39:20  来源:igfitidea点击:

What is the meaning of local variable hides a field?

java

提问by MikeV

So this is just a part of my code, and the entire program compiles and works, but I keep getting "local variable hides a field" next to lines three consecutive lines starting with "GameBoard myBoard = this.getGameBoard();. I'm just curious what that actually means and if it is doing anything to my program in the long run.

所以这只是我代码的一部分,整个程序都可以编译并运行,但是我一直在以“GameBoard myBoard = this.getGameBoard();”开头的三行连续行旁边出现“局部变量隐藏字段”。我'我只是好奇这实际上意味着什么,以及从长远来看它是否对我的程序有任何影响。

public void initialze(){
    myBoard = getGameBoard();
    obstacleLocations = myBoard.getObstaclePositions();
    pastureLocations = myBoard.getPasturePositions();

GameBoard myBoard = this.getGameBoard();
    ArrayList<GameLocation> obstacleLocations = myBoard.getObstaclePositions();
    ArrayList<GameLocation> pastureLocations = myBoard.getPasturePositions();
    GameLocation closestPasture = pastureLocations.get(0);
    GameLocation closestObstacle = obstacleLocations.get(0);

采纳答案by Dawood ibn Kareem

It means you've got two different variables with the same name - myBoard. One of them is a field in your class. Another one is a local variable, that is, one that you've declared inside a method.

这意味着您有两个具有相同名称的不同变量 - myBoard。其中之一是您班级中的一个字段。另一个是局部变量,即您在方法中声明的变量。

It's a bad idea to have two variables with the same name. It can make your code very confusing and difficult to maintain.

有两个同名的变量是个坏主意。它会使您的代码非常混乱且难以维护。

回答by JFPicard

The local variable in a method is always the variable with the highest visibility. That's why in a class setter you always do something like:

方法中的局部变量始终是具有最高可见性的变量。这就是为什么在类二传手中你总是做这样的事情:

void setId(String id) {
    this.id = id;
}

The this.idtells Java to assign the id(from the parameter) to the field variable. That's why this will not work:

this.id通知Java来分配id(从参数)字段变量。这就是为什么这不起作用:

void setId(String id) {
    id = id;
}

Since it'll assign idto itself.

因为它会分配id给自己。

You can read about scope, see: http://www.java-made-easy.com/variable-scope.htmlfor an example.

您可以阅读有关范围的信息,请参阅:http: //www.java-made-easy.com/variable-scope.html的示例。