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 » 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:

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: 7593
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Casting classes: Compiler vs Runtime Exceptions

Post by admin » Sun Feb 01, 2015 12:13 am

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.

sonal2391
Posts: 6
Joined: Thu Nov 29, 2018 1:15 am
Contact:

Re: Casting classes: Compiler vs Runtime Exceptions

Post by sonal2391 » Mon Dec 03, 2018 11:48 pm

The least complex meaning of a compiler is a program that interprets code written in an abnormal state programming dialect (like JavaScript or Java) into low-level code (like Assembly) specifically executable by the PC or another program, for example, a virtual machine.

For instance, the Java compiler changes over Java code to Java Bytecode executable by the JVM (Java Virtual Machine). Different precedents are V8, the JavaScript motor from Google which changes over JavaScript code to machine code or GCC which can change over code sent in programming dialects like C, C++, Objective-C, Go among others to local machine code.

Post Reply

Who is online

Users browsing this forum: No registered users and 3 guests