Object type cast in Java

Viewed 66

I'm struggling to understand the C() object created in this code.

I understand that when it is created on line 3, it is an object with the reference in the A class. I also understand that you can reference the same object on line 4 from a reference in the B class. However, I don't understand the casting of reference o1 on line 4. Does this change the object or just how it is referenced?

Would really appreciate an explanation :) thanks

public class TestClass{
   public static void main(String args[ ] ){
      A o1 = new C( );
      B o2 = (B) o1;
      System.out.println(o1.m1( ) );
      System.out.println(o2.i );
   }
}
class A { int i = 10;  int m1( ) { return i; } }
class B extends A { int i = 20;  int m1() { return i; } }
class C extends B { int i = 30;  int m1() { return i; } }
1 Answers

In

A o1 = new C( );

you assign an object of type C to a variable of type A.

o1 can reference any object of class A or any sub-class of A (such as B and C). However, once you assign an object of class C to a variable of type A, you can only use that variable to execute methods declared in class A (or any super class of A).

If you want to execute methods of class B, you must tell the compiler that this variable actually references an object of class B (which is true, since that variable holds a reference to an object of class C, which is also of class B, since C extends B).

That's what the cast is for:

B o2 = (B) o1;

Now, using the variable o2, you can call methods declared in class B.

However, since all 3 classes declare a method of the same signature (int m1( )), the cast doesn't allow you to call a method you couldn't call via the o1 variable. It does, however, give you access to the instance variable i of class B (by writing o2.i).

Does this change the object or just how it is referenced?

It doesn't change the object. It just gives the compiler more detailed information about the actual type of the object referenced by that variable.

Related