我有 Rectangle
和 Circle
类。它们都扩展了Shape
。 Object
类保存对 Shape
的引用。
现在我想访问 object.shape.vertices
如果 shape 是 矩形
或
对于圆
object.shape.radius
。
我不想在 Shape
类中保存半径/顶点等值,因为半径永远不会在 矩形
中使用。
最佳答案
您可以使用 instanceof
运算符检查对象是否属于某种类型,然后转换为该类型。
double value = 0.0;
if (shape instanceof Circle) {
Circle circle = (Circle)shape; // Cast the shape to a Circle
value = circle.radius;
} else {
// If it's not a circle, then it's a rectangle
Rectangle rectangle = (Rectangle)shape; // Cast the shape to a Rectangle
value = (double)rectangle.vertices;
}
但是,instanceof
运算符的使用应受到限制。我建议您在 Shape
类中创建一个返回适当字段的方法。
class Shape {
public double getValue() {
return 0.0;
}
}
class Circle {
public double radius;
@Override
public double getValue() {
return radius;
}
}
class Rectangle {
public int vertices;
@Override
public double getValue() {
return (double)vertices;
}
}
使用上面的示例,我们可以将第一个代码示例缩短为
double value = shape.getValue();
这种方法遵循多态性,并且最终更易于维护,因为忘记重写方法(如果使用抽象方法就不可能忘记)比添加新的 instanceof
更难检查代码中的其他位置。
如果您了解抽象类和方法,我建议您将 Shape
类及其方法抽象化。
关于java - 如何从父类(super class)引用的子类获取数据?形状 -> 矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31860268/