Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the superclass's version of a method have to be called before any of the subclass method's code?

I'm asking out of curiosity rather than necessity. I imagine the answer is something like "Because that's how Java was built". I'm wondering why that way was chosen.

So for instance, if my superclass has this method:

public void foo()
{
   System.out.println("We're in the superclass.");
}

And the subclass overrides the method:

@Override
public void foo()
{
   super.foo();
   System.out.println("We're in the subclass.");
}

Why is it required for super.foo() to be at the top of the subclass's method (if it's going to be used)? Why can't I swap the two lines to make it look like this:

@Override
public void foo()
{
   System.out.println("We're in the subclass.");
   super.foo();
}
like image 531
Lee Presswood Avatar asked Oct 27 '25 17:10

Lee Presswood


1 Answers

It doesn't. It does for constructors but for ordinary methods you can call it whenever you want to. You don't even have to call it if you don't want to, or you can call a different parent class method altogether.

From your example:

public static void main(String[] args) {
    new B().foo();
}

static class A {
    public void foo() {
        System.out.println("In A");
    }
}

static class B extends A {
    public void foo() {
        System.out.println("In B");
        super.foo();
    }
}

Outputs

In B
In A
like image 73
tddmonkey Avatar answered Oct 30 '25 06:10

tddmonkey