C3.java

Download this source file

// Demo of Shadowing.  In Java a class or instance variable in one class
// can "hide" or "shadow" one in a child or subclass.  The keywords
// "this" and "super" can be used to distinguish between local variables,
// class or instance variables, and variables that were inherited.
//
// Note that unlike with instance methods there is no polymorphism for
// variables, so the final printout is "c1.i = 1" and not "c1.i = 3".
//
// Written 3/2003 by Wayne Pollock, Tampa Florida USA.

class C1
{
   int i = 1;
}

class C2 extends C1
{
   int i = 2;
}

class C3 extends C2
{
   int i = 3;

   public void someMethod ( )
   {
       int i = 4;
       
       System.out.println( "i = " + i );
       System.out.println( "this.i = " + this.i );
       System.out.println( "super.i = " + super.i );
//     System.out.println( "super.super.i = " + super.super.i );  // No good!

       C1 c1 = new C3();
       System.out.println( "c1.i = " + c1.i );  // No polymorphism!
   }

   public static void main (String [] args )
   {
     C3 foo = new C3();
     foo.someMethod();
   }
}

Send comments and questions to pollock@acm.org.
Valid HTML 4.01!   Valid CSS!   CAST: Bobby WorldWide Approved 508   CAST: Bobby WorldWide Approved AAA