I am referencing this duplicate question here:
Check if a Class Object is subclass of another Class Object in Java
I have an abstract parent class named 'Figure' of which I have two subclasses, 'Circle' and 'Rectangle' both of which extend this abstract parent. I am trying to determine if a Figure object is of type Circle or type Rectangle.
My original code was:
public boolean isInstanceOfRectangle(Figure figure)
{
boolean isInstance = figure instanceof Rectangle;
System.out.println("instance of rectangle!");
return isInstance;
}
After studying the linked question above, I have rewritten my code as follows:
public boolean isRectangle()
{
boolean isInstance = Figure.class.isAssignableFrom(Rectangle);
System.out.println("instance of rectangle!");
return isInstance;
}
For some reason this does not work unless I include the following in my main class:
public Class<?> Rectangle;
public Class<?> Circle1;
I'm not sure the significance of including this in my class, if I do not, it seems to require that I include it as a parameter in my method. I am unable to correctly invoke and test this method because I am unsure what parameter to pass into the method when invoked. I'd like to write something like:
public void mouseReleased(MouseEvent e)
{
if ((isRectangle(shape1)))
addRectangle((Rectangle)shape1, e.getComponent().getForeground());
else if ((isCircle(shape1)))
addCircle((Circle) shape1, e.getComponent().getForeground());
}
where 'shape1' is a Figure object that was instantiated as either a circle or a rectangle. Because the parameter is of type Figure, I am unsure how to define the 'isRectangle' method to take a Figure object (the abstract parent) and determine specifically which subclass it is an instance of. Or preferrably to take no parameter and just do the work by using the Figure object to invoke the method. I am a bit confused how to proceed.
*Edit: upon user suggestions, I have rewritten the following which does NOT appear to work because in both cases the output is 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;
}