Quick Index
Variable Scope


Assume we are coding at "//CODING HERE".

Our variable scope is:

  • Local Variables (newWidth and newHeight)
  • Method Parameters (f1)
  • Instance Variables (width and height)

Our scope does not include variables in other methods (like reduceBy, newWidth, newHeight).
public class Rectangle {
private int width;
private int height;
public reduce(int reduceBy) {
	int newWidth;
	int newHeight;
}
public void applyFactor(int f1) {
	int newWidth;
	int newHeight;
	//CODING HERE"
}
Declare Then Use Local Variables
Local variables in a method must be declared before they are used.

See example here...


Context Boxes


Think Inside the Box
We are coding at "//CODING HERE".

Our variable context includes:

  • The box for the method we are coding in ("applyFactors")
  • The next outer box for the class "Rectangle"

Our context excludes other methods (like "reduce").
public class Rectangle { private int width; private int height;
public reduce(int reduceBy) { int foo; int moo; }
public void applyFactors(int factor1, int factor2) { int zoo, yoo; //CODING HERE }
Example Problem
We are using four variables.

  • Two compile okay
  • But two cause compile errors

Based on the previous step:

  • Why do the two work?
  • Why do the two fail?
public class Rectangle { private int width; private int height;
public reduce(int reduceBy) { int foo; int moo; }
public void applyFactors(int factor1, int factor2) { int zoo, yoo; zoo = 10; //okay yoo = 20; //okay foo = 30; //Compile Error moo = 40; //Compile Error }