Page 1 of 1

Casting classes: Compiler vs Runtime Exceptions

Posted: Fri Jan 30, 2015 7:19 am
by jmrego
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:

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;
    }
    
}
Here the compiler does not accept the cast and says that B cannot be converted to C :

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;
    }
 }
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?

Re: Casting classes: Compiler vs Runtime Exceptions

Posted: Sun Feb 01, 2015 12:13 am
by admin
You seem to have pasted the same code twice.
But basically yes, when a compiler can spot that something just cannot happen at runtime in any case, it flags an error.