Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of local variable hides a field?

Tags:

java

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.

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);
like image 726
MikeV Avatar asked Apr 23 '15 19:04

MikeV


2 Answers

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.

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

like image 167
Dawood ibn Kareem Avatar answered Oct 03 '22 08:10

Dawood ibn Kareem


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.id tells Java to assign the id (from the parameter) to the field variable. That's why this will not work:

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

Since it'll assign id to itself.

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

like image 21
JFPicard Avatar answered Oct 03 '22 07:10

JFPicard