![]() The reason that (Redwood) new Tree() gives a runtime exception and not compilation error is that that is what the JLS (section 5.5.1) says should happen. Strictly speaking, the compiler does not "issue casting exceptions". I have doubt when compiler will issue casting exception at compiler level and when it will be at runtime? This is most clearly demonstrated with an example: if (t instanceof Redwood)īut I would also add: Casting from a base type to a derived type is a bad thing. It takes an object on the left side of the operator and a type on the right side of the operator and returns a boolean value indicating whether the object belongs to that type or not. The instanceof operator allows you determine the type of an object. The casting/coercing operation is used to convert between types and the instanceof operator is used to check for type information at run time.* I would like to suggest you to use instanceof operator: ![]() But at run time due to Redwood r = (Redwood)t, where t is a object of Tree class if became faulty. that's the reason of runtime error.Ĭompiler do not now what is value in t and syntactically every thing is write. You can think this as follows: Tree t = new Tree() `īut really Redwood subclass can't point to Tree supper class object. Source Redwood r = (Redwood) new Tree() fist create Tree object and typecast to Redwood. Redwood r = (Redwood) new Tree() why no compiler error? You need to explicitly type cast a Tree object if it really points to either Redwood or Blackwook object, other wise it error at runtime. We need explicitly type cast.ĭowncast Example: Redwood r = new Tree() //compiler error, because Tree is not a Redwoodīlackwood r = new Tree() //compiler error, because Tree is not a Blackwood When we cast a reference along the class hierarchy in a direction from the root class towards the children or subclasses. We need not use a cast operator in this caseĪ Redwood or Blackwood both are tree: So Tree t1 When we cast a reference along the class hierarchy in a direction from the sub classes towards the root. I added one more subclass of in my explanation.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |