Prerequisites: this reference and inner class in Java.
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:
Java
// Java program to demonstrates Shadowing in Java // Outer Class public class Shadowing { // Instance variable or member variable String name = "Outer John" ; // Nested inner class class innerShadowing { // Instance variable or member variable String name = "Inner John" ; // Function to print content of instance varible public void print() { System.out.println(name); System.out.println(Shadowing. this .name); } } // Driver Code public static void main(String[] args) { // Accessing an inner class Shadowing obj = new Shadowing(); Shadowing.innerShadowing innerObj = obj. new innerShadowing(); // Function Call innerObj.print(); } } |
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:
Java
// Java program to demonstrates Shadowing in Java // Outer Class public class Shadowing { // Instance variable or member variable String name = "Outer John" ; // Nested inner Class class innerShadowing { // Instance variable or member variable String name = "Inner John" ; // Function to print the content public void print(String name) { System.out.println(name); System.out.println( this .name); System.out.println(Shadowing. this .name); } } // Driver Code public static void main(String[] args) { // Accessing an inner class Shadowing obj = new Shadowing(); Shadowing.innerShadowing innerObj = obj. new innerShadowing(); // Function Call innerObj.print( "Parameter John" ); } } |
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.