Why should the superclass method version be called before any of the subclass method code?

I'm asking out of curiosity, not necessity. I guess the answer is something like "Because Java is built this way". I am wondering why this path was chosen.

So, for example, 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 to super.foo()

be at the top of the subclass method (if used)? Why can't I swap two lines so they look like this:

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

      

+3


source to share


1 answer


This is not true. This is done for constructors, but for normal methods, you can call it whenever you want. You don't even need to call it if you don't want to, or you can call another method of the parent class altogether.

In 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

      

+7


source







All Articles