Casting classes: Compiler vs Runtime Exceptions

Moderator: admin

Post Reply
jmrego
Posts: 8
Joined: Wed Dec 10, 2014 6:05 am
Contact:

Casting classes: Compiler vs Runtime Exceptions

Post 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?

admin
Site Admin
Posts: 10240
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Casting classes: Compiler vs Runtime Exceptions

Post 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.
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: No registered users and 2 guests