Java Reference
In-Depth Information
cakeHeight = 50;
int cakeHeight;
cakeHeight = 5;
me.chat( "2) cake height is " + cakeHeight); // Print it
makeCakes(me);
}
}
public void makeCakes(Player me) {
me.chat( "3) cake height is " + cakeHeight); // Print it
Location loc = me.getLocation();
loc.setY(loc.getY() + 2);
setBlockAt(loc, BlockType.Stone);
for ( int i = 0;i < cakeHeight;i++) {
loc.setY(loc.getY() + 1);
setBlockAt(loc, BlockType.Cake);
}
}
}
When run, this code will print out the value of cakeHeight three times. Notice
that there are two declarations of the variable cakeHeight , one at and
another at .
What will this code print out, and how many cakes will end up in the tower?
Try to figure it out first. Then compile and install using build.sh as usual.
What Happened?
Welcome to the wonderfully confusing world of shadowing .
In this piece of code, a variable named cakeHeight is declared at the top of the
plugin. This is the variable you would expect to access anywhere within the
plugin—starting on that line and ending at the matching closing brace, } .
But then on the line at we declare another variable with the very same
name. From this point until the next closing brace, }, any time we mention
cakeHeight we'll be working with this local one, not the class-level one. This
local version shadows the class version. So when we set it to 5 and then print
it, we're modifying this local version.
Calling makeCakes then uses the class version to build the tower. The makeCakes
function has no knowledge of the shadowed variable inside the cakeTowerCommand
function. So you end up with fifty blocks; not a hundred, and not five.
 
 
Search WWH ::




Custom Search