| Can you define variable shadowing in Java with example?
If any of instance variable and the local variables have the common same name. And when we access this variable then it will print the local variable which will shadowing the instance variable. Below are the some reasons for considering a variable shadowing.
(i)When method is overridden in the child class.
(ii)When subclass declares a variable with same name of the parent class variable.
(iii)There are some situation where a variable in local scope with same name as the name of a variable defined in and instance scope.
Below is the example for variable shadowing
public class testShadowing
{
string name="interviewqsn";
int subject=12;
public void displaylocal()
{
string name="crackyourinterview";
int subject=20;
System.out.println("Name:-" + name);
System.out.println("subject:-" + subject);
}
public static void main(String args[])
{
new testShadowing().displaylocal();
}
}
Output:-
Name:- crackyourinterview
subject:- 20 | | |