在Java中,将对象向上转型后,之前的引用还能访问该对象吗?

huangapple go评论71阅读模式
英文:

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

赋值不会复制对象 - 它会从b1b2复制对对象的引用

您可能会发现我在解释变量、引用和对象之间区别的答案也很有帮助。

英文:

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.

huangapple
  • 本文由 发表于 2020年9月5日 15:01:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/63751329.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定