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?
– 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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With