-
Junior Member
-
Junior Member
Re: Need for Down cast
hi ramharibhat ,
this is a short note from Khalid mugal about downcasting, If u need more then refer this book for more help. one of the best book for core java.
DownCasting
Casting the value of a superclass reference to a subclass type is called downcasting . This is illustrated by assigning references down the inheritance hierarchy, which requires explicit casting.
stringRef = (String) objRef; // (8)
System.out.println("(9): " + stringRef.equals("C++")); // (9)
At (8), the source reference objRef is of type Object, which is the superclass of the class of the destination reference stringRef. If the reference objRef actually denoted an object of class String at runtime, the cast would convert it to the proper subclass type, so that the assignment to the reference stringRef would be legal at (8). The reference stringRef could then be used to invoke the equals() method on this String object, as at (9). Not surprisingly, the equals() method from the String class would be executed.
The compiler verifies that an inheritance relationship exists between the source reference type and the reference type specified in the cast. However, the cast can be invalid at runtime. If, at runtime, the reference objRef denotes an object of class Object or some unrelated subclass of class Object, then obviously casting the reference value to that of subclass String would be illegal. In such a case, a ClassCastException would be thrown at runtime. The instanceof operator (see Section 6.6, p. 264) can be used to determine the runtime type of an object before any cast is applied.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules