1

A have some code where I'm suppose to identify why the runtime type of subscribeAsBase is not taken into account in one case, but matters in another case.

My theory is: The runtime type of subscribeAsBase is not taken into account when invoking selectMethod() because it is set as BaseClass object and SubClass extends BaseClass. After trying the other invocations we could see that if selectMethod() was called on subscribeAsBase the runtime type mattered, as it then is seen as a SubClass.

Here is the code:

public class Polymorphism {

    public static void main(String[] args) {
        BaseClass baseObject = new BaseClass();
        SubClass subscribe = new SubClass();
        BaseClass subscribeAsBase = new SubClass();
        baseObject.selectMethod(subscribeAsBase); // here runtime type of the subscribeAsBase doesn't matter
        subscribeAsBase.selectMethod(subscribe); // here the runtime type matters
    }
}
public class BaseClass {

    public void selectMethod(SubClass x) {
        System.out.println(MessageFormat.format(
                "BaseClass.selectMethod(SubClass {0})", x));
    }

    public void selectMethod(BaseClass x) {
        System.out.println(MessageFormat.format(
                "BaseClass.selectMethod(BaseClass {0})", x));
    }

    @Override
    public String toString() {
        return "'A Base object'";
    }

}
public class SubClass extends BaseClass {

    public void selectMethod(SubClass x) {
        System.out.println(MessageFormat.format(
                "SubClass.selectMethod(SubClass {0})", x));
    }

    public void selectMethod(BaseClass x) {
        System.out.println(MessageFormat.format(
                "SubClass.selectMethod(BaseClass {0})", x));
    }

    @Override
    public String toString() {
        return "'A Subclass object'";
    }

}
Agent smith 2.0
  • 112
  • 2
  • 12
  • 1
    I believe what you're getting at is static vs dynamic binding. Java binds statically always. In the case of `baseObject.selectMethod(subscribeAsBase);` The type of the *variable* (not the potentially more specific runtime type) `subscribeAsBase` is used to determine which method signature should be called at compile-time. Some other languages support dynamic binding at runtime. It can be a big performance impact. – Michael Sep 06 '21 at 13:14
  • 1
    @Michael More specifically, the type of the _expression_: Static binding applies even if no variable is involved. – chrylis -cautiouslyoptimistic- Sep 06 '21 at 14:17

0 Answers0