What is variable shadowing used for in a Java class?

The basic purpose of shadowing is to decouple the local code from the surrounding class. If it wasn’t available, then consider the following case.

A Class Foo in an API is released. In your code you subclass it, and in your subclass use a variable called bar. Then Foo releases an update and adds a protected variable called Bar to its class.

Now your class won’t run because of a conflict you could not anticipate.

However, don’t do this on purpose. Only let this happen when you really don’t care about what is happening outside the scope.

Leave a Comment