Questions...
I need to do the following:
See if x belongs to the Rectangle class.
See if x is a subclass of the JPanel class, but not the JPanel class itself.
See if x implements the Cloneable interface.
The following are my current answers:
a)
x.getClass() == Rectangle.class
b)
x instanceof JPanel.class
c)
x instanceof Cloneable
But I'm not sure about them...
I also thing that b) could also be x.getSuperClass() == JPanel.class
But an issue with this in part a is, for example, if x is actually a Rectangle class thing, then the statement evaluates as true... but if it is not, then the program wouldn't even compile.
I'm not really sure about this, so any help would be good.
Posts
Also, I don't see why the program wouldn't compile if x.getClass() == Rectangle.class evaluates as false.
And for your b), if x cannot be a JPanel, then I guess you'd need to add
&& x.getClass() != JPanel.class
or something
Edit :
When you use instanceof, don't use .class on the Class ... so : x instanceof JPanel
Here's the compile error it gives me if, say, x is a Polygon and I ask it if it == Rectangle.class:
Incomparable types: java.lang.Class<java.awt.Polygon> and java.lang.Class<capture of ? extends java.awt.Rectangle>
Weird... I can run this code :
And it prints false without any errors.
If it keeps failing though, try using x.getClass().equals(Rectangle.class) and see if it fixes the problem.
Edit:
It seems that type comparisons that will always return false are not allowed by the compiler... Perhaps I have an older version. That's a pretty weird behavior.
However, using .equals() works perfectly fine.
Any explanations for that?
.equals is what you should use. object.getClass().equals(object.getClass()); or object.getClass().equals(Clazz.class);
B.net: Kusanku
a)
x.getClass().equals(Rectangle.class)
b)
x instanceof JPanel && !x.getClass().equals(JPanel.class)
c)
x instanceof Cloneable
Those seem to be working fine. Not sure about c though...? Seems valid, but is there a better way?
Also, while I'm at it... any idea how I could explain why the compiler doesn't check for ArrayStoreErrors at compile time? I understand why it's not doing it in my specific case, we had to write a sample program that generated one of those errors, and I can explain it for that specific case:
public class ShapeArrayProgram{
public static void main(String[] args) {
Rectangle[] r = new Rectangle[5];
Shape[] s = r;
s[1] = new Polygon();
}
}
Because the compiler only checks for sub/supertype compatability? Is that a valid way to explain why it is like that?
B.net: Kusanku