4

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();
}
Ankush soni
  • 1,439
  • 1
  • 15
  • 30
Lee Presswood
  • 210
  • 2
  • 15
  • The answer (in case of constructors) is exactly because "the Java language says so" :) – meskobalazs Aug 06 '15 at 14:52
  • 3
    It isn't required at all. Go ahead, swap the lines and it'll work. Only for constructors and that's quite reasonable. Note that apart from constructors (where the language makes it mandatory to call `super()`), it is a code smell to require calls to `super.foo()` from an override of `foo()`. – biziclop Aug 06 '15 at 14:52

1 Answers1

7

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
tddmonkey
  • 20,798
  • 10
  • 58
  • 67
  • You forgot to mention the reason for `why so in the case of constructors it is necessary to call super() first?` – Am_I_Helpful Aug 06 '15 at 14:55
  • @shekharsuman there is no need to "because", since the assumption of the question is wrong :). – Vincenzo Pii Aug 06 '15 at 14:56
  • @shekharsuman Constructors weren't part of the question but if you want to, write an answer, every bit of information helps. – biziclop Aug 06 '15 at 15:00
  • 1
    @biziclop - Ok, I found an answer for the same already here, so I won't be writing a new one. For the case of constructor, please check this one ---> http://stackoverflow.com/a/26169094/3482140 – Am_I_Helpful Aug 06 '15 at 15:04