Variable shadowing in Java

If there exists two variables with the same name in a particular scope, one of the variables take the priority while the other one gets hidden or shadowed. This is also known as Variable Shadowing in Java. In the following snippet, we can find the same thing happening.

B is a subclass and A is its superclass. Note that A has one instance variable initialized as i=10, while B which inherits the properties and behaviour of class A, has the instance variable with the same name initialized as i=20. Its obvious that we expect the overriding to happen as for the methods, but NO!

There are a couple of important things to note before we go ahead –

  • Methods are overridden. Overriding never happens for variables, they are just inherited.
  • Access to a variable depends on the reference class, and not on the class of the actual object.

The output that we see is –

Now let’s modify our code a bit. Let’s comment out line numbers 5 and 12.

The output now turns out to be –

Now if you truly can understand the above code snippets, then you are through the concept of variable shadowing.

Having the same variable names for instance and local variables is a bad coding practice and must be avoided.

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.