javaoophierarchysuperclass

Why is superclass method calling overrided subclass method when the superclass method is the one specified to be called?


Here i have the following Java code example, where i'm expecting "I'm A class" from A class method1(Integer arg) to be printed in main:

public class A {

    public void method1(String arg) {
                //some number passed, not important
        this.method1(1);
    }
    public void method1(int arg) {
        System.out.println("I'm A class");
    }
}
public class B extends A{

    @Override
    public void method1(String arg) {
        super.method1(arg);
    }
    @Override
    public void method1(int arg) {
        System.out.println("I'm B class");
    }
}
public class MainAB {

    public static void main(String[] args) {
        B b = new B();
                //some string passed, not important
        b.method1("HI");
    }
}

So as i understand, the flow of the calls should be: B class, method1("HI") -> A class, method1("HI") -> A class, method1(1) -> print: "I'm A class"

But for some reason it goes from A class to B class and method1(1) from B class is being called, and "I'm B class" is printed.

Am i missing something? How can i solve this? Thanks


Solution

  • the flow of the calls should be: B class, method1("HI") -> A class, method1("HI") -> A class, method1(1) -> print: "I'm A class"

    No, the correct flow is:

    B class, method1("HI") -> A class, method("HI") -> B class method1(1) -> print: "I'am B class"

    "I'am B class" - is printed because method1(int arg) is overridden in B class.

    This is how Runtime Polymorphism work in Java, method invocation is decided based on the type of the object and not by the type of reference. The type of your object is B so the method1(int arg) of B is called.

    You could prevent overriding method1(int arg) by making it final.