Casting classes: Compiler vs Runtime Exceptions
Posted: Fri Jan 30, 2015 7:19 am
I'm trying to understand how the java compiler analyse the code and i'm having some troubles finding when the compiler detects an error in casts.
Here the compiler accepts the cast and JVM launches an exception:
Here the compiler does not accept the cast and says that B cannot be converted to C :
This second case is easy to understand since there is no relation between an object of type B and an object of type C, meaning you can't have a reference type C pointing to an object of class B;
In the first case we have a reference of type A pointing to an object of class B. B and C has no relation, however A and C have a relation. How does the compiler verifies this and lets the error pass to JVM? In what situations the compiler trust the programmer? There must be some logic that i'm not understanding. It has something to do with the reference of the object?
Here the compiler accepts the cast and JVM launches an exception:
Code: Select all
class A {}
class B extends A {}
class C extends A {}
public class NewMain {
public static void main(String[] args) {
A a = new A();
A b = new B();
C C = (C) b;
}
}
Code: Select all
class A {}
class B extends A {}
class C extends A {}
public class NewMain {
public static void main(String[] args) {
A a = new A();
B b = new B();
C C = (C) b;
}
}
In the first case we have a reference of type A pointing to an object of class B. B and C has no relation, however A and C have a relation. How does the compiler verifies this and lets the error pass to JVM? In what situations the compiler trust the programmer? There must be some logic that i'm not understanding. It has something to do with the reference of the object?