Skip to content

Instantly share code, notes, and snippets.

@rshepherd
Last active August 28, 2020 04:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rshepherd/78eda49398af50db546f to your computer and use it in GitHub Desktop.
Save rshepherd/78eda49398af50db546f to your computer and use it in GitHub Desktop.
An example of the implications of Java's lexical scoping rules in the context of a class.
public class Scoping { // class scope begins
// Because 'a' is declared just inside the *class curly braces* it is in 'class scope'
// therefore its visible everywhere inside the class. This is the 'widest' scope in this file.
private int a = 0;
// Class variables have class scope!
private static String classVariable = "I am a class variable!";
public void methodOne() { // methodOne scope begins
// Because 'b' is declared inside the *methodOne curly braces*
// its only visible in methodOne
int b = 0;
if (a == b) { // conditional scope begins
// Because 'c' is declared inside conditional curly braces its only
// visible inside the conditional
int c = 1;
// Because 'b' is declared in a scope which surrounds the scope of
// the conditional, 'b' is visible.
b += c;
// Because 'a' is declared in a scope that surrounds this scope of
// the conditional, 'a' is visible.
a += c;
}
// 'c' is no longer visible
}
// 'b' no longer visible
public void methodTwo() { // methodTwo scope begins
int d = a;
// 'a' is is visible since its in a scope that surrounds this scope (class scope)
// 'b' & 'c' not visible, they are in a scope that does not surround the scope of this method
// 'd' only visible inside methodTwo
System.out.println(classVariable + " has class scope too, and is visible everywhere in the class.");
}
// 'd' no longer visible
// Note: Constructors obey the same rules as methods w.r.t. variable scoping
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment