简体   繁体   中英

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?

Your class hierarchy looks like this:

C  - > B  - > A  - >我

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

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:

在此输入图像描述 is a type of Programming_language , but Programming_language is not a type of 在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM