Thursday, January 26, 2012

Challenge 040’s Solution

Of the three, only statements 1 and 3 are valid. This is because of how the classes are written. The Dancer class contains the leap() method. The BalletDancer class is an extension of the Dancer class; thus, the BalletDancer class can be used to create Dancer objects and perform Dancer methods. However, the Dancer class cannot be used to create BalletDancer objects or perform BalletDancer-specific methods, like the glide() method. Object b is from the BalletDancer class—it can perform both the leap() method and the glide() method—so statement 1 is valid. However, object d is from the Dancer class—it can perform the leap() method, but not the glide() method—so statement 3 is valid, while statement 2 is invalid.

−Phoenix

3 comments:

  1. Check out the d.glide(); statement again.

    What will happen when glide() is called in this example? Will there be an error? If so, when and what kind? Use the compiler to test. Thank you.

    ReplyDelete
    Replies
    1. In BlueJ™, the statement “d.glide()” results in the error message “cannot find symbol - method glide()”. This is because the object “d”, while being created using the “BalletDancer()” constructor, is still thought of by BlueJ™ as a “Dancer” object; thus, “d” cannot perform “glide()”. To fix this, one can replace the statement “d.glide()” with “((BalletDancer)d).glide()”. This adjusts “d” to be a “BalletDancer” object; thus, “d” can perform “glide()”.

      −Phoenix

      Delete
    2. Perfect. 100 XPs awarded for this completion.

      Delete