[   ^ to index...   |   <-- previous   |   next -->   ]

Overriding vs. overloading

You learned about the difference between overriding and overloading in 143. However, you now have a better conceptual context in which you can appreciate the difference:

Imagine we used the Java EatingFly class hierarchy from the previous page. Which of the following lines would typecheck? For legal lines, which methods would get called?

    FruitEatingFly ffly = new FruitEatingFly();
    AppleEatingFly afly = ffly;
    Apple appleRef = new Apple();
    Fruit fruitRef = anApple;

    ffly.eat(appleRef);              //  1
    ffly.eat(fruitRef);              //  2
    afly.eat(appleRef);              //  3
    afly.eat(fruitRef);              //  4

Another consequence of the Java/C++ design

Recall from lecture that a class that inherits abstract methods from a superclass (or interface) must either (1) be declared abstract, or (2) implement the abstract methods. What is wrong with the following declaration of FruitEatingFly?

    abstract class AppleEater {
        abstract void eat(Apple a);
    }
    class FruitEatingFly extends AppleEater {
        void eat(Fruit f) { ... }
    }

"Generic functions"

Some of you may recall "generic functions" from lecture. A generic function is simply a function that, when called, dispatches to one of several methods which implement that generic function. One way to think about the Java overriding rules is that Java methods are generic functions grouped by exact match on the method name and argument types:

Receiver classes/methods
AppleEatingFly FruitEatingFly
Generic functions eat(Fruit f) ---(does not exist)--- FruitEatingFly::eat(Fruit f)
eat(Apple a) AppleEatingFly::eat(Apple a) FruitEatingFly::eat(Apple a)

Selection among generic functions happens at compile time. Selection among receivers/methods happens at runtime.


Keunwoo Lee
Last modified: Wed May 30 20:55:22 PDT 2001