Last active
August 28, 2020 04:56
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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