【发布时间】:2019-06-04 19:33:03
【问题描述】:
我在这里引用了这个重复的问题:
Check if a Class Object is subclass of another Class Object in Java
我有一个名为“Figure”的抽象父类,我有两个子类“Circle”和“Rectangle”,它们都扩展了这个抽象父类。我试图确定一个图形对象是圆形还是矩形类型。
我原来的代码是:
public boolean isInstanceOfRectangle(Figure figure)
{
boolean isInstance = figure instanceof Rectangle;
System.out.println("instance of rectangle!");
return isInstance;
}
在研究了上面的链接问题后,我重写了我的代码如下:
public boolean isRectangle()
{
boolean isInstance = Figure.class.isAssignableFrom(Rectangle);
System.out.println("instance of rectangle!");
return isInstance;
}
由于某种原因,除非我在主类中包含以下内容,否则这不起作用:
public Class<?> Rectangle;
public Class<?> Circle1;
我不确定将它包含在我的课程中的意义,如果我不这样做,似乎需要我将它作为参数包含在我的方法中。我无法正确调用和测试此方法,因为我不确定在调用时将什么参数传递给该方法。我想写一些类似的东西:
public void mouseReleased(MouseEvent e)
{
if ((isRectangle(shape1)))
addRectangle((Rectangle)shape1, e.getComponent().getForeground());
else if ((isCircle(shape1)))
addCircle((Circle) shape1, e.getComponent().getForeground());
}
其中“shape1”是一个被实例化为圆形或矩形的 Figure 对象。因为参数是 Figure 类型,我不确定如何定义“isRectangle”方法来获取 Figure 对象(抽象父对象)并具体确定它是哪个子类的实例。或者最好不带参数,只通过使用 Figure 对象调用方法来完成工作。我有点困惑如何进行。
*编辑:根据用户的建议,我重写了以下 ,这似乎不起作用,因为在这两种情况下,输出都是 FALSE。
Figure circleObj = new Circle(Color.BLUE);
System.out.println(isInstanceOfRectangle(circleObj));
System.out.println(isInstanceOfCircle(circleObj));
public static boolean isInstanceOfRectangle(Figure figure)
{
boolean isInstance = figure instanceof Rectangle;
if (isInstance == true)
System.out.println("instance of rectangle!");
else
System.out.println("is NOT a rectangle");
return isInstance;
}
public static boolean isInstanceOfCircle(Figure figure)
{
boolean isInstance = figure instanceof Circle;
if (isInstance == true)
System.out.println("instance of circle!");
else
System.out.println("is NOT a circle");
return isInstance;
}
【问题讨论】:
-
你应该几乎总是重组你的代码以避免需要这样做。
-
这两种情况都是错误的,因为您在这两种方法中都检查了
figure instanceof Rectangle。您应该在第二个中检查figure instanceof Circle。 -
正如@chrylis 提到的,您应该以这样的方式重组代码,以便您可以避免此类检查。一种选择是在 Figure 中创建一个抽象方法并在您的 Circle/Rectangle 类中覆盖它以执行您想要的行为。
标签: java object inheritance instance abstract-class