0

你好,

我有一个向下铸造的问题,我在这方面有点生疏。我有 2 节课是这样的:

class A{ int i; String j ; //Getters and setters}
class B extends A{ String k; //getter and setter}

我有一个这样的方法,在一个实用程序助手类中:

public static A converts(C c){}

其中 C 是从数据库中检索然后转换的对象。

问题是我想通过传入'C'并返回B来调用上述方法。所以我尝试了这个:

B bClasss = (B) Utility.converts(c);

因此,即使上述方法返回 AI 尝试将其向下转换为 B,但我得到了运行时 ClassCastException。真的没有办法解决这个问题吗?我是否必须编写一个单独的 converts() 方法来返回 B 类类型?

如果我像这样声明我的 B 类:

class B { String k; A a;} // So instead of extending A it has-a A, getter and setters also

然后我可以像这样调用我现有的方法:

b.setA(Utility.converts(c) );

这样我可以重用现有的方法,即使扩展关系更有意义。我应该怎么办?非常感谢任何帮助。谢谢。

4

4 回答 4

4

The cast from type A to type B:

B bClasss = (B) Utility.converts(c);

doesn't work because objects of type A don't have all the methods that might be called from references of type B. What would you expect to happen if you called

bClasss.getK();

on the next line? The underlying object has no member variable k, so this cast is not allowed.

You can use references of the higher types in your class hierarchy to refer to objects of lower types, but not the other way around.

Without knowing more, I think the best thing to do is implement multiple methods

A aObj = Utility.convertToA(c);
B bObj = Utility.convertToB(c);

If B extends A, then you should still benefit from some code reuse in the constructors of your classes.

于 2010-05-13T19:31:18.910 回答
2

这里重要的是 Utility.converts() 实际返回的内容 - 如果它不创建新的 B 对象并返回它,则无法从中获取 B 。

(因为你得到 ClassCastException,那么它不会在里面创建 B)

于 2010-05-13T19:14:43.383 回答
1

您应该在适当的抽象级别上工作,并编写您的方法签名来做同样的事情。如果 B 的公共/默认接口从 A 被大量修改,那么您的方法签名确实应该返回 B。否则,放弃尝试强制转换它,将 .converts 的结果分配给 A 类型的变量,然后处理它就像一个 A,即使它的真实类型实际上是一个 B。如果你试图在这里低调,你将失去通过继承进行抽象的意义。

在没有看到您的源代码的情况下,我不知道在这里使用组合代替继承是否有意义。上面的段落假设你所说的“扩展关系更有意义”是真的。

于 2010-05-13T19:23:40.560 回答
0

If your converts() method doesn't actually return a B, then there is no way to cast it to a B. Since you are getting a ClassCastException it clearly doesn't return a B.

You can of course write a converts(C c) that returns a B. But an alternative approach might be to write a constructor:

B(A a)

which creates a B based on the contents of A. Then you use converts to get a C, and create a B from it.

于 2010-05-13T19:33:52.540 回答