I am working with Java and trying to use 'instanceof' to determine if an object returned is an instance in a class. The code (not my code) I have to work with is layed out in this manner. The question is why instanceof cannot cast correctly to determine if the object is an instance of the class?
public class MainClass{
public static void main(String[] args){
Class1 myClass1 = new Class1();
if(myClass1.getObject() instanceof Class1){} ///<--- Cast Error
}
}
public class Class1 extends ObjectClass{
public InnerClass1 getObject(){
return (InnerClass1)object;
}
public static abstract class InnerClass1 extends Class2{}
}
public class Class2 {}
public class ObjectClass {
final Class2 object = new Class2();
}
As you can see the object is an instance of Class2. When calling the 'get' method it casts the object to type InnerClass1 which extends Class2. InnerClass1 is a subclass of Class1. The 'instanceof' check wants to check if the object is an instance of Class1 but it fails with a cannot cast error. Why is this? Thanks for help.
---EDIT--- Just a reminder, this is NOT my code. I was given this to work with and was just having some difficulty parsing through why the instanceof was not working. The answers were great and I understand now. Thanks!
Class2is not subclass ofInnerClass1.Class2is not a subclass in the first place.getObjectmethod first to a temporary reference, like:Object tempObject = myClass.getObject();you would see where the error is coming from. Try not to convolute your code to much as it often the cause of such misunderstandings as you now have.