Super Method Calls

February 11th, 2009

I really wanted to start this entry off with some sort of superman reference or joke, but everything I came up with was an order of magnitude past lame.

The notation of using super to call a method came up last night in class. Ok, technically it first showed up on a quiz, an unfortunate aspect my students are hopefully still not mad at me for (in my defense, I gave them all credit for that question when I realized my mistake). My explanation largely centered around a code sample in class that I wanted to make sure I cleaned up and made available.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Alpha {
    public void foo() {
        System.out.println("Alpha");
    }
}
class Beta extends Alpha {
    public void foo() {
        System.out.println("Beta");
    }
    public void printFoos() {
        foo();
        this.foo();
        super.foo();
    }
}

Assuming we created a Beta instance and called printFoos(), the following would be output::

1
2
3
Beta
Beta
Alpha

For the first two calls in printFoos(), the overridden foo() method in Beta is executed. Remember that the super keyword says to look to the parent class for the body of the method. In this case, we’re asking that Alpha’s implementation of foo() be called regardless of the fact that Beta overrides it.

Comments are closed.