classcastexception - How does class casting work? -


consider c1 base class of c3. below code works perfectly.

    c1 obj1=new c3();     c3 obj2=(c3)obj1; 

but, there classcastexception in below one

    c1 obj1=new c1();     c3 obj3=(c3)obj1; 

what have missed?

i think what's happening creating obj1 instance of c1, , trying cast class further down inheritance chain c1.

in first example, c1 base type of c3 , can create instance of c3 type c1..that's fine. c3 child of c1 , inherits properties , methods.

in 2nd example, however, creating instance of c1 type of c1. trying cast child. child class may have additional properties , methods parent doesn't have.

to summarise, child can of parent type , cast it, however, parent cannot child , cannot cast such.

if need further clarification, let me know.


Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -