我有一个名为 Shape 的父类(super class):
abstract class Shape {
private String color;
public Shape(String color) {
this.color=color;
}
public String getColor(){return color;}
abstract double Area();
}
和两个继承类:
class Rectangle extends Shape {
private double b,h;
public Rectangle(double b,double h, String color) {
super(color);
this.b=b;
this.h=h;
}
public double getB() { return b;}
public double getH() { return h;}
public double Area() {
return b*h;
}
}
class Circle extends Shape {
private double r;
public Circle(double r,String color) {
super(color);
this.r=r;
}
public double getR() {
return r;
}
public double Area() {
return 3.14*r*r;
}
}
现在我已经创建了一个对象或形状(矩形和圆形)的数组。我遇到的问题是当我想迭代该数组的元素并打印它们的属性时。我想做这样的事情:
for (int i=0;i<lengthShapes;i++) {
System.out.println(shapes[i].getB()+shapes[i].getH()+shapes[i].getR());
}
我的意思是如何识别第 i 个位置的对象是矩形或圆形以打印其属性,请记住我只有一个形状数组。我认为我可以使用接口(interface)来做到这一点,但是如何仅使用抽象类来做到这一点。那可能吗? 谢谢
最佳答案
I mean how I can do to recognize that the object in the ith position is a Rectangle or a Circle ...
最简单的方法是使用 instanceof
运算符。
例如
if(shapes[i] instanceof Rectangle) {
Rectangle rect = (Rectangle) shapes[i];
// ...
}
这不被认为是一个好的做法(这些都是您自己的类,但您仍然必须检查对象的类型(在运行时)并使用显式转换)。
但是如果您只想打印属性,那么您可以让两个子类覆盖 toString()
正确地然后你就可以做 -
System.out.println(shapes[i]);
关于java - 如何识别对象数组中对象的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16879617/