Witscale Test Center

11.3 Method overloading and overriding > 11.3.4 Methods are overridden but variables are shadowed


11.3.4 Methods are overridden but variables are shadowed

When you declare a method with the same signature as some inherited method in superclass, the method is said to be overridden. So what happens if you declare a member variable with the same name as some inherited variable? Is it overridden just like the method? Let us assume that Camera class in our earlier example has member variable named defaultFilmSpeed. The subclass also defined a member variable with the same name. Figure 11.11 illustrates the two classes.


 

Figure 11.11 Variables of superclass can be shadowed and methods can be overridden in subclass (using the same name)

 

Due to late binding, when a method is called (on an object reference), the actual method invoked depends on the type of object in that reference. The Tester class is creating an object of SLRCamera and storing it in variable of Camera type. Therefore when myCamera.shoot() is called, the method in SLRCamera is called. However, when a member variable is accessed through an object reference, the variable to be selected depends on the type of that variable. Since the type of myCamera is Camera, myCamera.defaultFilmSpeed will be resolved as 100. Thus, variables are not exactly overridden. They are said to be shadowing the variable (with same name) in the superclass. From the subclass, you can still see the redefined variable. For example, from within SLRCamera class, the variable defaultFilmSpeed will be 400. If we define the myCamera variable of type SLRCamera, then also the myCamera.defaultFilmSpeed will be resolved as 400.