Quiz 4 (Exercises from Chap. 9)

  1. Suppose the class Sandwich implements the Edible interface. Which of the following assignments are legal?
    Sandwich sub = new Sandwich() ;
    Edible e = sub ;                              // 1
    Rectangle box = new Rectangle(5, 10, 20, 30) ;
    Edible f = box ;                              // 2
    f = (Edible) box ;                            // 3
    sub = e ;                                     // 4
    sub = (Sandwich) e ;                          // 5
    sub = (Sandwich) box ;                        // 6
    
  2. How does a cast such as (BankAccount) x differ from a cast of number values such as (int) x? Formulate your answer in terms of potential information loss?




  3. The classes Rectangle2D.Double, Ellipse2D.Double and Line2D.Double realize the Shape interface. The Graphics2D class depends on the Shape interface but not on the rectangle, ellipse and line classes. Draw a UML diagram denoting these facts.
    .
    .
    .
    .
    .
    .
    .
    .
    
    
  4. Suppose r contains a reference to a new Rectangle(5, 10, 20, 30). Which of the following conditions is true? If you look in the API you will see that Rectangle is part of an inheritance chain which goes: java.awt.Rectangle, java.awt.geom.Rectangle2D, java.awt.geom.RectangularShape, java.lang.Object, and the implemented interfaces are Shape, Serializable, Cloneable.
  5. Classes such as Rectangle2D.Double, Ellipse2D.Double and Line2D.Double realize the Shape interface. The Shape interface has a method
    Rectangle getBounds()
    that returns a rectangle completely enclosing the shape. Consider the method call:
    Shape s = . . . ;
    Rectangle r = s.getBounds() ;
    
    Explain why this is an example of polymorphism.