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);
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With