Shadowing in Java is the practice of using variables in overlapping scopes with the same name where the variable in low-level scope overrides the variable of high-level scope. Here the variable at high-level scope is shadowed by low-level scope variable.
Let’s have a look at the example below:
Inner John Outer John
In this example, you can see that name is declared as String variable inside Shadowing class as well as innerShadowing class. When we print just name then it prints the value of name stored at innerShadowing class because the scope of this class is less than outer class so it overrides the value of the name.
Let’s have a look at another example which will clarify the concept more clearly:
Parameter John Inner John Outer John
In this example, we pass the argument to the print() method. So we can see now for printing the name of the inner class we need to use ‘this’ because the scope of the print() method is less than that of inner class so it overrides the name of the inner class too.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.