C3.java

Download C3.java

 1: // Demo of Shadowing.  In Java a class or instance variable in one class
 2: // can "hide" or "shadow" one in a child or subclass.  The keywords
 3: // "this" and "super" can be used to distinguish between local variables,
 4: // class or instance variables, and variables that were inherited.
 5: //
 6: // Note that unlike with instance methods there is no polymorphism for
 7: // variables, so the final printout is "c1.i = 1" and not "c1.i = 3".
 8: //
 9: // Written 3/2003 by Wayne Pollock, Tampa Florida USA.
10: 
11: class C1
12: {
13:    int i = 1;
14: }
15: 
16: class C2 extends C1
17: {
18:    int i = 2;
19: }
20: 
21: class C3 extends C2
22: {
23:    int i = 3;
24: 
25:    public void someMethod ( )
26:    {
27:        int i = 4;
28: 
29:        System.out.println( "i = " + i );
30:        System.out.println( "this.i = " + this.i );
31:        System.out.println( "super.i = " + super.i );
32: //     System.out.println( "super.super.i = " + super.super.i );  // No good!
33: 
34:        C1 c1 = new C3();
35:        System.out.println( "c1.i = " + c1.i );  // No polymorphism!
36:    }
37: 
38:    public static void main (String [] args )
39:    {
40:      C3 foo = new C3();
41:      foo.someMethod();
42:    }
43: }