Results 1 to 2 of 2

Thread: Need for Down cast

  1. #1
    Junior Member
    Join Date
    Jun 2006
    Answers
    2

    Arrow Need for Down cast

    Hi everybody, can any one tell me what is d need for 'down cast' that is going down the inheritance hierarchy of the classes, is their any place for downcasting to be placed inside real time coding..


  2. #2
    Junior Member
    Join Date
    Nov 2006
    Answers
    26

    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
  •  
About us
Applying for a job can be a stressful and frustrating experience, especially for someone who has never done it before. Considering that you are competing for the position with a at least a dozen other applicants, it is imperative that you thoroughly prepare for the job interview, in order to stand a good chance of getting hired. That's where GeekInterview can help.
Interact