Concrete Class implements a interface. Typecasted to Interface later. How does JVM recognize the Typecasted instance?
A Concrete class typecasted to interface, does JVM still consider it a instance of concrete class ?
When you create an assignment, the type of the assignment is inferred based on the type given. E.g. MyInterface mi = new MyImplementation(); mi in this case is typed as the interface, but refers to the implementation. The JVM will know that the instance points to an implementation if you do instance of.
Before I answer the specific question, note that implementations of interfaces are can be passed anywhere the interface type is accepted. i.e. if Impl implements Interface, Impl isA interface, so why would you cast to the interface type? It would be completely unnecessary. I have seen situations where you would cast to a specific implementation, but not from implementation to interface, and even those situations are dicey.
I had to verify this with the following code, but no, if you have an interface implementation, and you cast it to the interface, anything that requires the implementation will get a compile time error if you try to pass as the interface. Here is the code
public class Runner {
public static void main(String[] args) {
ExampleImpl impl = new ExampleImpl(); // never do this in real life
// Example impl = new ExampleImpl() <-- do this instead "code to the interface"
Example casted = (Example) impl;
takesExampleImpl(casted); // compile error because takesImpl expects the implementation
takesExampleImpl(impl); // works because impl is an implementation
takesExampleImpl((ExampleImpl)casted); // works because I cast it back to imple
}
public static void takesExampleImpl(ExampleImpl instance){
}
static class ExampleImpl implements Example {
public void testMethod() {
System.out.println("impl");
}
}
}
Example is just a simple interface with one method, code not shown.
Also, note that my code answers the question, it does a lot of things wrong--you wouldn't see code like that in a professional setting (or you shouldn't at least). The point of interfaces is so that you can define the behavior, and just pass in an object that conforms to that behavior. So you would not write a method that accepted an implementation, you would write a method that accepted the interface, to which you could pass anything that provided the implementation. That way you can pass different implementations to the same method as the need might arise.
精彩评论