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 really confusing, which is the best way to figure out if I can reset or raise an object?

+5
source share
2 answers

Your class hierarchy is as follows:

C -> B -> A -> I

An object x can be run in class Y if the execution type x is a subclass of Y Or, in other words, if there is a path from the runtime type from x to Y By "runtime type" I mean the type of the object (the one used to construct the object), as opposed to the type of the variable (the one indicated in the variable declaration).

It's really:

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

An object stored in b is of type b . It is discarded to I , and then returns to b . b is a subclass of both of them. Transferring to I does virtually nothing and is intended only to confuse you.

However, none of them are valid:

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

Both failures are excluded: java.lang.ClassCastException: A cannot be cast to B a is of type a , which is not a subclass of b . There is a relationship between a and b , but it is in the opposite direction - b is a subclass of a .

See here for more details: http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

+1
source

The only thing you need to answer the question in your coding example is this:

 class B extends A{} 

This means that B is a subclass of A. Subclasses can be assigned to superclass classes, but the superclass cannot be classified as subclass types.

Therefore, A cannot be applied to type B.

Why? Think of logic as follows:

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

+1
source

Source: https://habr.com/ru/post/1210329/


All Articles