What happens when there is a local variable with the same name as an instance or static variable?
Here is some sample code to illusrate what happens:
package ScopeVariables; import absolutely.nothing_else.can.go.here; //only imports can be outside a class public class BigMainClass { //Global variables //*** DO NOT NEED TO BE INITIALIZED. //*** CAN BE ACCESSED FROM ANYWHERE IN THIS CLASS static String president = "Trump"; static int myStaticInt; String day = "Monday"; int myInstanceInt; int speed = 8; //static methods static void myStaticMethod() { System.out.println("I'm a static method."); } //instance methods void myInstanceMethod(int qwerty) { myInstanceInt = qwerty; System.out.println("I'm instance method #" + myInstanceInt); } void move() { speed ++; } //constructors BigMainClass() { System.out.println("I am a constructor for BigMainClass"); } //main public static void main(String[] args){ //also a static method System.out.println("myStaticInt is " + myStaticInt); //myInstanceInt = 7; //ERROR: because: cannot access instance things from a static thing. BigMainClass bm1 = new BigMainClass(); bm1.myInstanceMethod(5); Child cc = new Child(); // System.out.println("speed = " + bm1.speed); bm1.move(); cc.move(); System.out.println("speed = " + cc.speed); System.out.println("speed = " + bm1.speed); new MiniClass().miniMethod(); System.out.println("myStaticInt is " + myStaticInt);//shadowing static variables System.out.println("\n\nThe president is " + president); //TRUMP String president = "Clinton"; //now president is shadowed; I've created a local variable with the same name System.out.println("The president is " + president); ` //CLINTON System.out.println("No, The president is " + BigMainClass.president); //TRUMP//shadowing instance variables //System.out.println("Today is " + day); // ERROR Must do this in an instance context ... bm1.shadow(); //OTHER ERRORS: Local variables int fingers; //fingers = fingers + 2; //ERROR: fingers is not initialized. MiniClass zeta; //zeta.miniMethod(); //ERROR: null pointer error if zeta is global variable; uninitialized error if it is a local variable } void shadow() { System.out.println("\nA static variable: " + president); System.out.println("Today is " + day); day = "--unknown--"; System.out.println("Today is " + day); String day = "Tuesday"; //now day is shadowed System.out.println("No, today is " + day); System.out.println("Actually today is " + this.day); } } class MiniClass { void miniMethod() { //since the variable is not private, I can access it in another class in the same package. BigMainClass.myStaticInt++; } } class Child extends BigMainClass{ Child() { speed = super.speed + 6; } }