0

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?

  • 1
    The variable `b` and the object it refers to are not affected by your assigning the same object to `a`. – khelwood Sep 05 '20 at 07:03

1 Answers1

1

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Oh bang-on reply! Got it within the first line. Thanks for the quick clarification, @Jon –  Sep 05 '20 at 07:05
  • @shadyshamus: Goodo - I've added a bit more explanation to help anyone else who finds this :) – Jon Skeet Sep 05 '20 at 07:06