2.15 Shadowing Variables2.14 Calling Overridden Methods2 Java with Caffeine2.16 Final Methods and Classes

2.15 Shadowing Variables

A child class may not only override methods of the parent class, it may also redefine variables inherited from the parent class, a technique that is called  shadowing a variable. For instance, we may declare

   class Article
   {
     int number;
     String title;
     int price;
     ...
   }

   class Book extends Article
   {
     float price;
     String author;
     String publisher;
     String ISBN;
     ...
   }

Here the child class Book declares a new float variable price in addition to the int variable declared in the parent class. We now have two variables of the same name; any reference to price within class Book refers to the locally declared float variable which thus shadows the int variable declared in the class Article. Nevertheless, we may still refer to the int variable using the notation super.price (like we may refer to overridden methods).

Having said this, there is no good reason to ever shadow a variable. It makes

Shadowing variables can and should be avoided.
code difficult to understand and we can always choose a new name for a variable in a child class.
© Wolfgang Schreiner; February 3, 2005

2.15 Shadowing Variables2.14 Calling Overridden Methods2 Java with Caffeine2.16 Final Methods and Classes