Lets imagine I have a class called Person which is a generalization of another class Man. If I am to make a couple of instances of this class
Man man = new Man();
Person person = new Man();
Now, the compile-time class of the instance being referenced from the variable man is Man and the compile-time class of person is Person while the run-time class of both instances is Man. So far, im completely on board with the terminology because the instances which are created at run-time both are of class Man. But, if I where to cast the man instance as follows
Person personMan = (Person) man;
how come the run-time type of personMan is still Man? Is the run-time class of a instance only set when a new instance is created? Also, is there a way of actually getting the compile time class of a variable at runtime, so I could query what type of class personMan is (getClass would return Man).
Edit: “compile-time class of a class” was a mistake (and doesn’t make much sense). What I meant was variable (hence they question about what type of class personMan is :))
It’s important to distinguish between three different concepts here:
man,person)The type of an object never changes after it’s created. Casting a reference to a different type only affects the compile-time type of that expression. The result of a reference-type cast expression is always the same the original reference – it still refers to the same object, which still has the same type. (That’s leaving boxing aside – and of course the cast can fail at execution time, leading to an exception.)
If you mean the compile-time type of a variable – not if it’s a local variable, without really deep inspection of the byte code. If it’s a field you can use reflection to get at it. Why do you want to know?