1

Let's say i have the following classes :

public class Foo {

     public Foo()
     {}

     public String who() {
         return "I'm foo ";
     }

    public String info() {
        return who() + "and i provide foo infos";
    }

    public static void main(String[] args)
    {
        Foo bar = new Bar();
        System.out.println(bar.info());
    }
}

and

public class Bar extends Foo {

    public Bar() {
        super();
    }

    public String who(){
        return "I'm bar ";
    }

    public String info(){
        return super.info() + " about x";
    }
}

Expected output : "I'm foo and i provide foo infos about x"

Real output : "I'm bar and i provide foo infos about x"

As far as i know, super() refers to the parent object, so i'm expecting that when super.info() calls the "who" method, it's the parent's "who" method that's called, but it appears that it's child "who" method that's effectively called.

Could you explain me this particular behavior ?

Side question : if i wanted to do my behavior (call parent's method), is it possible ?

1 Answers1

3

info() is calling who(), and because class Bar has its own who() method, this one is called. In runtime, you have a Bar instance, so every method is looked in this instance first, and only if the instance doesn't have the method, the parent class is "invoked" (i.e the method is looked in the parent class).

You can debug the code and see it yourself

Guy Smorodinsky
  • 902
  • 7
  • 16