Shadowing is a common concept in java. It may refer to classes or variables. The concept of shadowing comes when a variable of same name overlaps within different scopes. For example :
public class A{
int z = 10;
system.out.println(z);
public void M()
{
int z = 20;
system.out.println(z);
}
}
Output :
10
20
In the above example we saw clearly that the variable z is same in class and method level but its scope are different. When we try to print the variable from the method , the value 20 is printed . So here the variable of higher- scope level is hidden and variable of lower scope overrides it. This is called shadowing.
Similarly this concept is used as class level too. When we use nested class then the variable in the parent class is suppressed by the variable of the nested inner class. For Example :
public class A{
int z = 10;
system.out.println(z);
public class B{
int z = 20;
system.out.println(z);
public void M()
{
int z = 30;
system.out.println(z);
}
}
}
Again the variable z is same in 2 different classes and 1 method but its scope is limited. When we call a lower lever variable it suppresses the higher ones.
public class A{
int z = 10;
system.out.println(z);
public void M()
{
int z = 20;
system.out.println(z);
}
}
Output :
10
20
In the above example we saw clearly that the variable z is same in class and method level but its scope are different. When we try to print the variable from the method , the value 20 is printed . So here the variable of higher- scope level is hidden and variable of lower scope overrides it. This is called shadowing.
Similarly this concept is used as class level too. When we use nested class then the variable in the parent class is suppressed by the variable of the nested inner class. For Example :
public class A{
int z = 10;
system.out.println(z);
public class B{
int z = 20;
system.out.println(z);
public void M()
{
int z = 30;
system.out.println(z);
}
}
}
Again the variable z is same in 2 different classes and 1 method but its scope is limited. When we call a lower lever variable it suppresses the higher ones.
No comments:
Post a Comment