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
  • 1
    The variable b and the object it refers to are not affected by your assigning the same object to a.
    – khelwood
    Sep 5, 2020 at 7:03

1 Answer 1

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.

2
  • Oh bang-on reply! Got it within the first line. Thanks for the quick clarification, @Jon
    – user11991978
    Sep 5, 2020 at 7:05
  • @shadyshamus: Goodo - I've added a bit more explanation to help anyone else who finds this :)
    – Jon Skeet
    Sep 5, 2020 at 7:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.