英文:
Is an object accessible from a previous reference after it has been upcast (in Java)?
问题
A是一个父类。让B和C成为它的子类。
A a;
B b = new B(args);
a = b;
类型为B的对象仍然可以通过b访问,还是已经永久性地向上转型为A类型?
英文:
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
强制类型转换不会改变对象本身。它只是为您提供了一种“以不同方式看待对象”的方式(将其视为“A”而不是“B”)。但它们是同一对象的不同视角。通过a
进行的任何更改将通过b
可见,依此类推。
没有进行类型转换时也是如此。例如,如果存在一对具有明显行为的setValue
/getValue
方法,您将会看到:
B b1 = new B(args);
B b2 = b1;
b1.setValue(10);
System.out.println(b2.getValue()); // 10
赋值不会复制对象 - 它会从b1
到b2
复制对对象的引用。
您可能会发现我在解释变量、引用和对象之间区别的答案也很有帮助。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论