Join AllAdvantage.com

WEBrewery


Tip #7: Accessing Shadowed Variables Beyond the Immediate Superclass

In Java, you can access a shadowed variable from the immediate superclass by using the keyword super. Several people have asked me if it is possible to access a shadowed variable beyond the immediate superclass in Java. The answer is yes. Chaining the keyword super will not work in Java. The solution is to do a cast of the keyword this. Here is a code snippet I wrote demonstrating how it works:

     class A
     {
          int n = 111;
     }

     class B extends A
     {
          int n = 222;
     }

     class C extends B
     {
          int n = 333;

          int x = n;
          int y = ((B)this).n;
          int z = ((A)this).n;
     }

     public class ShadowTest
     {
          public static void main(String args[])
          {
               C c = new C();

               System.out.println(c.x);
               System.out.println(c.y);
               System.out.println(c.z);
          }
     }

The output of the above code snippet would be:

     333
     222
     111


For Beginners | Jargon | General Tips | Swing | Books | Links | WEBrewery.com

Java is a trademark of Sun Microsystems.

Copyright © 1999 WEBrewery. All rights reserved.
Reproduction in whole or in part in any form or medium without
the express written permission of WEBrewery is prohibited.
brewer@webrewery.com

Dell laptop power cord

Dell laptop power cord

www.dell-laptop-powercord.com

Communicatie adviesbureau

communicatie adviesbureau

www.connexx.nl