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?