Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting in Java(interface and class)

if:

interface I{}

class A implements I{}

class B extends A{}

class C extends B{}

A a = new A();
B b = new B();

Why a = (B)(I)b; is correct
but b = (B)(I)a; is false?

I find casting to be very confusing, what is the best way to understand if I can down cast or up cast an object?

like image 946
OPK Avatar asked Oct 31 '22 12:10

OPK


2 Answers

Your class hierarchy looks like this:

C -> B -> A -> I

Object x can be casted to class Y, if runtime type of x is subclass of Y. Or, in other words, if there is a path from runtime type of x to Y. By "runtime type" i mean the type of object (the one used when constructing object) as opposed to type of variable (the one from variable declaration).

This is valid:

b = new B();
(B)(I)b;

Object stored in b has type B. It's casted to I and then back to B. B is a subclass of both of them. Cast to I doesn't actually do anything and is meant only to confuse you.

However, neither of those is valid:

a = new A();
(B)(I)a;
(B)a;

They will both fail with exception: java.lang.ClassCastException: A cannot be cast to B. a has type A which is not a subclass of B. There is a relation between A and B, but it's in the opposite direction - B is a subclass of A.

For more detailed explanation see here: http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

like image 159
Piotr Praszmo Avatar answered Nov 13 '22 03:11

Piotr Praszmo


The only thing of relevance to answering the question in your coding sample is the following:

class B extends A{}

This means that B is a subclass of A. Subclasses can be cast to super class types, but super class cannot be cast to subclass types.

Therefore, A cannot be cast to type B.

Why? Think about the logic this way:

enter image description here is a type of Programming_language, but Programming_language is not a type of enter image description here

like image 35
Jobs Avatar answered Nov 13 '22 03:11

Jobs