Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

explain this output about Object reference casting? [duplicate]

interface I {
}
class A {
}
class B {
}
public class Test {
    public static void main(String args[]) {
        A a = null;
        B b = (B)a; // error: inconvertible types

        I i = null;
        B b1 = (B)i;
    }
}

i know why a can not be cast to B, because of B is not inherit from A.
my question is about, why B b1 = (B)i; is allowed since B is not implements from I ?
and why B b1 = (B)i; this line will not force a runtime exception since i is null?

like image 535
Kalhan.Toress Avatar asked Apr 02 '14 15:04

Kalhan.Toress


People also ask

What determines the casting of object references in Java?

– The casting of object references depends on the relationship of the classes involved in the same hierarchy. Any object reference can be assigned to a reference variable of the type Object, because the Object class is a superclass of every Java class.

How to cast an object reference to an interface reference?

If you implement an interface and provide body to its methods from a class. You can hold object of the that class using the reference variable of the interface i.e. cast an object reference to an interface reference.

What is the difference between a reference variable and a cast?

Reference variables are different; the reference variable only refers to an object but doesn’t contain the object itself. And casting a reference variable doesn’t touch the object it refers to, but only labels this object in another way, expanding or narrowing opportunities to work with it.

How do you cast an object to another object in Java?

In java object typecasting one object reference can be type cast into another object reference. The cast can be to its own class type or to one of its subclass or superclass types or interfaces. There are compile-time rules and runtime rules for casting in java.


Video Answer


1 Answers

The compiler doesn't know everything about your class hierarchy. As far as it's concerned, there could be class B2 extends B implements I, in which case the above cast would need to work.

like image 71
Jeffrey Avatar answered Sep 24 '22 04:09

Jeffrey