Inner class means one class that is a member of another class. There are basically four types of inner classes in java. Nested Inner class can access any private instance variable of the outer class. Like any other instance variable, we can have access modifier private, protected, public, and default modifier.
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 the low-level scope variable. Basic knowledge of this keyword is required before moving ahead.
Implementation:
Here we will be discussing a few examples to get a better understanding of the concept as we will be able to perceive it better alongside code and later will discuss how the output is generated.
Example 1
Java
class Shadowing {
String name = "Outer John" ;
class innerShadowing {
String name = "Inner John" ;
public void print()
{
System.out.println(name);
System.out.println(Shadowing. this .name);
}
}
}
class GFG {
public static void main(String[] args)
{
Shadowing obj = new Shadowing();
Shadowing.innerShadowing innerObj
= obj. new innerShadowing();
innerObj.print();
}
}
|
Output
Inner John
Outer John
Output explanation:
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 that will clarify the concept more clearly as follows:
Example 2
Java
class Shadowing {
String name = "Outer John" ;
class innerShadowing {
String name = "Inner John" ;
public void print(String name)
{
System.out.println(name);
System.out.println( this .name);
System.out.println(Shadowing. this .name);
}
}
}
class GFG {
public static void main(String[] args)
{
Shadowing obj = new Shadowing();
Shadowing.innerShadowing innerObj
= obj. new innerShadowing();
innerObj.print( "Parameter John" );
}
}
|
Output
Parameter John
Inner John
Outer John
Output explanation:
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.
Last Updated :
30 Aug, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...