假设我有一个超级类型(Shape)和两个孩子(如Square,Circle).
我想做这样的事情:
Shape shape = someObject.getShape();
if (shape instanceof Square){
shape = (Square) shape;
// do this
} else if (shape instanceof Circle) {
shape = (Circle) shape;
// do that
}
Run Code Online (Sandbox Code Playgroud)
此外,由于获取实例似乎不是正确的OO原则,还有另一种方法吗?干杯.
编辑.我不是试图在它们上调用方法,我想将它们传递给一些需要特定子类型的方法.
edit2基本上我有一个Shape类型的集合,所以我可以在其中包含两种类型的子类型.但是当涉及到一点处理时,我需要知道这两个子类中的哪一个,所以我可以将它传递给一个将子类型作为参数的方法.我可以轻松地使用超类型作为参数,但这不安全,因为我处理特定于子类型的数据.
您需要正确声明变量,例如:
if (shape instanceof Square){
Square square = (Square) shape;
// do this with square
} else if (shape instanceof Circle) {
Circle circle = (Circle) shape;
// do that with circle
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2728 次 |
| 最近记录: |