Variable Shadowing

Variable shadowing occurs when a local variable (inside a method, constructor, or block) has the same name and type as an instance variable (declared at the class level). In this case, the local variable takes precedence within its scope. However, you can still access the instance variable using the this keyword.
Syntax to access instance var in local scope: this.variablename
Example
class Employee{
double salary=150000.0; // instance var declared in global scope
public void info()
{
//local variable declared in local scope
double salary = 40000.0;
System.out.println(salary); // it prints 40000.0
double temp = this.salary;
System.out.println(temp); // it prints 150000.0
}
public static void main(String[] a)
{
Employee e =new Employee();
e.info();
}
}
Subscribe to my newsletter
Read articles from SAMEERNA directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
