class A
class B
class CastingUpAndDown
1: // CastingUpAndDown.java
3: import java.io.*;
5: class A
6: {
7: protected int i = 2;
8: public A(){}
9: public int function()
10: {
11: return 2*i;
12: }
13: }
15: class B extends A
16: {
17: protected int i = 3;
18: public B(){}
19: public int function()
20: {
21: return 3*i;
22: }
23: }
26: class CastingUpAndDown
27: {
28: static PrintWriter screen = new PrintWriter(System.out, true);
30: static public void main(String[] args) throws IOException
31: {
32: A objectA;
33: B objectB = new B();
35: screen.println("\nValue of i from class B = " + objectB.i);
36: screen.println("Value of function from class B = " +
37: objectB.function());
39: // Cast objectB to an instance of class A
40: objectA = (A)objectB;
42: screen.println("\nYou may refer to shadowed variables by " +
43: "casting an object of the appropriate type:");
44: screen.println("Value of i from class A = " + objectA.i);
45:
46: screen.println("\nYou cannot refer to overriden methods by " +
47: "casting an object to the appropriate type.");
48: screen.println("Value of function is still from class B = " +
49: objectA.function() +"\n");
50: }
51: }