I was trying to use getClass() method and have the following code:
class parent{}
class child extends parent{}
public class test {
public static void main(String[] args){
child b= new child();
System.out.println(b.getClass()==parent.class);
}
}
I got a compiling error saying Incompatible operand types Class<capture#1-of ? extends child> and Class<parent>
, and it is ok if I initilize b with Object b= new child();
. Can anyone tell me what is the difference between them?
Thanks in advance.
Since the introduction of generics in Java 5, the java.lang.Class
class is generic on the type that it represents. This enables constructing object through their Class
without a cast, and enables other useful idioms.
That's why the compiler can get too smart, and see that it is able to evaluate the expression entirely at compile time: your expression is always false
. The compiler gives you the type compatibility error, but that's a direct result of the expression being compile-time constant.
One way to avoid this is through using java.lang.Object
as the type. Once you do that, the compiler can no longer evaluate the type of getType
's result precisely, thus avoiding the error.
Another way to fix this problem would be casting the return type to a non-generic Class
System.out.println(((Class)b.getClass())==parent.class);
or using an intermediate variable of the non-generic kind:
Class bClass = b.getClass();
System.out.println(bClass==parent.class);
That error message basically means that the compiler can tell when it's compiling the program that the answer to that equality check will always be false. Since it knows the child class and the parent class can never be equal it refuses to compile the code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With