CS 310, Object-Oriented Programming with Java

Quiz 6, 28 February 2008


  1. The max() method accepts two objects and returns the larger of the two based on the result of Comparable.compareTo(). Illustrate with code the difference between implementing

    Object max(Object a, Object b)
    

    and

    Object max(Comparable a, Comparable b)
    

    Hint: in either case, max() implementation has a one (possibly compound) statement.


    Given object parameters, max() has to downcast them to Comparables and then test:

    Object max(Object a, Object b)
      if ((Comparable a).compareTo(b) < 1)
        return b;
      else
        return a;
    

    Given Comparable parameters, no downcasting is needed:

    Object max(Object a, Object b)
      return a.compareTo(b) < 1 ? b : a;
    

    Interfaces, page 214 (7th ed.) or 244 (8th ed.).

  2. Explain why you should favor interfaces over abstract classes.


    Interfaces allow a form of multiple inheritance, while abstract classes do not (Interfaces and Abstract Classes, page 218 (7th ed.) or 249 (8th ed.)).


This page last modified on 31 March 2008.