Is an object accessible from a previous reference after it has been upcast (in Java)?



Say A is a parent class. Let B and C be its child classes.

A a;
B b = new B(args);
a = b;

Is the type B object still accessible via b, or has it been permanently upcast to type A?

Answer

The cast doesn’t change the object at all. It just gives you “a different way of seeing the object” (viewing it as an “A” instead of a “B”). They’re different views on the same object though. Any changes you make via a will be visible via b etc.

The same is true without the cast. For example, if there’s a setValue/getValue pair of methods with the obvious behavior, you’d see:

B b1 = new B(args);
B b2 = b1;
b1.setValue(10);
System.out.println(b2.getValue()); // 10

The assignment doesn’t copy the object – it copies a reference to the object from b1 to b2.

You may find my answer explaining the difference between a variables, references and objects helpful too.



Source: stackoverflow