Calling an overridden superclass method from a subclass

public class F {
    protected int a=0, b=0;
   public F() {
     a = 2;
     b = 2;
     }
  public void increase() {
     upA();
  } 
  public void upA() {
     a = a + 1;
  }
  public String toString() {
     return a+" "+b;
   }
 }

 public class G extends F {
      public void increase() {
            super.increase();
            upB();
      }
     public void upA() {
            a = a + a;
     }
     public void upB() {
          b = b + 1;
   }
 }

What is printed in the Output window by the following Java fragment?

 G g = new G();
 g.increase();
 System.out.println(g);

Can someone explain to me why the answer is 4,3

(ie. the subclass method is called even though I have called super.increase() which calls the upA method in the superclass?)

Jon Skeet
people
quotationmark

All your methods are being called virtually, with overrides applying. So this code in F:

public void increase() {
    upA();
} 

... is invoking G.upA(), because the object it's calling upA() on is an instance of G.

So the execution flow for increase() is:

  • G.increase() calls super.increase()
    • F.increase() calls upA()
    • G.upA() executes (so a = 4)
  • G.increase() calls upB()
    • G.upB() executes (so b = 3)

people

See more on this question at Stackoverflow