object - Type casting/Down casting in Java -
i'm trying clarify understand type casting. please correct me on incorrect i've been self learning java 2 months @ slow pace.
let's created class called subobject. , aware classes not have direct explicit superclass, assumed subclasses of object class.
object obj1 = new subobject(); subobject subobj1 = (subobject) obj1; system.out.println(subobj1); //prints out com.examplepackage.subobject1234e1234; so have downcasted reference of base class (object) derived class (subobject). however...
object obj2 = new object(); subobject subobj2 = (subobject) obj2;//this throws classcastexception error. my understanding of classcastexception error it's inherited runtimeexception catch during compile time, show code has attempted cast object subclass of not instance. because subobj2 not instance of subobject, rather object, incompatible.
so have 2 questions: 1. there flaw/error in understanding? 2. in situation downcasting used? everyone.
the relevance of runtimeexception 'unchecked'. developer not forced deal it. normal approach check (using if statement , using instanceof) see if cast allowed before allowing cast.
so,
if(subobj2 instanceof subobject) { subobject s2 = (subobject) obj2; ... } however, considered 'code smell' -- i.e. unusual , rings alarm bells in minds of senior developers. should achieving sort of thing through polymorphism, though that's not possible or desirable. types of programs, type casting should not necessary of time.
however, thinking broadly correct.
Comments
Post a Comment