Calling base class overridden function from base class method

Maxim Veksler picture Maxim Veksler · Jan 29, 2011 · Viewed 35.8k times · Source
public class A {
    public void f1(String str) {
        System.out.println("A.f1(String)");
        this.f1(1, str);
    }

    public void f1(int i, String str) {
        System.out.println("A.f1(int, String)");
    }
}



public class B extends A {
    @Override
    public void f1(String str) {
        System.out.println("B.f1(String)");
        super.f1(str);
    }

    @Override
    public void f1(int i, String str) {
        System.out.println("B.f1(int, String)");
        super.f1(i, str);
    }
}


public class Main {
    public static void main(String[] args) {
        B b = new B();
        b.f1("Hello");
    }
}

I'm seeking that this code would output:

B.f1(String)
A.f1(String)
A.f1(int, String)

Yet I'm getting:

B.f1(String)
A.f1(String)
B.f1(int, String)
A.f1(int, String)

I understand that under the context of B "this" in A.f1(String) is B's instance. Do I have the option to do the chain new B1().f1(String) -> (A's) f1(String) -> (A's) f1(int, String) ?

This is a theoretical question, practically the solution would obviously be in A to implement a private function that both f1(String) and f1(int, String) would call.

Thank you,
Maxim.

Answer

Bert F picture Bert F · Jan 29, 2011

Unfortunately, no