Casting variables in Java -


i wonder if tell me how casting works? understand when should it, not how works. on primitive data types understand partially when comes casting objects don't understand how works.

how can object type object cast to, let's say, mytype (just example) , methods?

casting in java isn't magic, it's telling compiler object of type of more specific type b, , gaining access methods on b wouldn't have had otherwise. you're not performing kind of magic or conversion when performing casting, you're telling compiler "trust me, know i'm doing , can guarantee object @ line <insert cast type here>." example:

object o = "str"; string str = (string)o; 

the above fine, not magic , well. object being stored in o string, , therefore can cast string without problems.

there's 2 ways go wrong. firstly, if you're casting between 2 types in different inheritance hierarchies compiler know you're being silly , stop you:

string o = "str"; integer str = (integer)o; //compilation fails here 

secondly, if they're in same hierarchy still invalid cast classcastexception thrown @ runtime:

number o = new integer(5); double n = (double)o; //classcastexception thrown here 

this means you've violated compiler's trust. you've told can guarantee object of particular type, , it's not.

why need casting? well, start need when going more general type more specific type. instance, integer inherits number, if want store integer number that's ok (since integers numbers.) however, if want go other way round need cast - not numbers integers (as integer have double, float, byte, long, etc.) , if there's 1 subclass in project or jdk, create , distribute that, you've no guarantee if think it's single, obvious choice!

regarding use casting, still see need in libraries. pre java-5 used heavily in collections , various other classes, since collections worked on adding objects , casting result got out collection. however, advent of generics of use casting has gone away - has been replaced generics provide safer alternative, without potential classcastexceptions (in fact if use generics cleanly , compiles no warnings, have guarantee you'll never classcastexception.)


Comments

Popular posts from this blog

cakephp - simple blog with croogo -

How to group boxplot outliers in gnuplot -

bash - Performing variable substitution in a string -