lundi 6 septembre 2021

Why do runtime type matters in some cases and not in others? [duplicate]

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'";
    }

}

Aucun commentaire:

Enregistrer un commentaire