将一个Object对象转换为不同类型的对象?

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

Turn an object of Object into an object of different type?

问题

不确定问题是否有意义,但基本上我要做的是这样的:

Object obj = new Object();
BankAccount s = (BankAccount) obj;
System.out.println(s instanceof BankAccount);

我希望这返回true,但它抛出一个类转换异常错误。为什么我不能将BankAccount转换为Object?是因为BankAccount自动成为Object的子类吗?

英文:

Not sure if the question makes sense, but basically what I'm trying to do is this

Object obj = new Object();
BankAccount s = (BankAccount) obj;
System.out.println(s instanceof BankAccount);

I want this to return true, but it throws me a class cast exception error. Why can I not cast BankAccount to Object? Is it because BankAccount is automatically a subclass of Object?

答案1

得分: 3

类型转换在告诉编译器:“你认为这个 obj 的类型是 Object,但请相信我,它实际上是一个 BankAccount”。但事实是,你在那方面撒了谎,因为它并不是。该实例只是一个 Object。下面的代码是有效的:

Object obj = new BankAccount();
BankAccount s = (BankAccount) obj;
System.out.println(s instanceof BankAccount);
英文:

The type cast is telling the compiler "you think this obj has type Object, but trust me, it is actually a BankAccount". But you were lying about that, because it wasn't. The instance was only an Object.

The following would work:

Object obj = new BankAccount();
BankAccount s = (BankAccount) obj;
System.out.println(s instanceof BankAccount);

答案2

得分: 1

除了Henry的评论解释了你可以执行以下操作:

Object obj = new BankAccount();
BankAccount s = (BankAccount) obj;
System.out.println(s instanceof BankAccount);

你应该始终记住,变量就像是一种遥控器。

第一行使用一个Object遥控器来控制一个BankAccount。这是可能的,因为所有东西都是一个Object... 这意味着你可以使用这个遥控器来控制所有对象。但你还会注意到,这个遥控器只支持在Object类中定义的操作,这意味着所有的Object都有这些操作。

等式右边的第二行声明了引用的Object实际上是一个BankAccount。在等式的左边,你强制创建一个新的遥控器,可以控制BankAccount对象。

英文:

In addition to Henry's comment who explained that you could do the following:

Object obj = new BankAccount();
BankAccount s = (BankAccount) obj;
System.out.println(s instanceof BankAccount);

You should always keep in mind that variables are some kind of remote control.

The first line uses a Object remote control to control a BankAccount. This is possible because everything is an Object... this means you can use this remote control to control all objects. But you will also see that this control only supports operations that are defined in the Object class which means all Objects have.

The second line at the right side of the equation states that the referenced Object is actually a BankAccount. On the left side of the equation you force to create a new remote control that is able to control BankAccount objects.

huangapple
  • 本文由 发表于 2020年9月24日 11:44:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/64039219.html
匿名

发表评论

匿名网友

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

确定