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();
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With