简体   繁体   中英

how polymorphism method matches in java

I'm puzzled how Java polymorphism works. In the case below, there are three polymorphism methods of showText , for distinguishing clearly, these methods names method-1 , method-2 , method-3 . codes as below:


public class PolymorphismTest {
    public static void main(String[] args) {
        showText("def");
    }

    // method-1
    private static void showText(Object abc) {
        print("1.....");
        showText(abc, "abc");
    }

    // method-2
    private static void showText(Object abc, String item) {
        // print(abc.getClass().getName());
        print("2.....");
        String text;
        if (abc == null) {
            text = null;
        } else {
            text = abc.toString();
        }
        showText(text, item);
    }

    // method-3
    private static void showText(String abc, String item) {
        print("3.....");
    }

    private static void print(String text) {
        System.out.print(text);
    }
}

  • method-1 has one parameter of type Object
  • method-2 has two parameters, the parameter type are Object and String
  • method-3 has two parameters, the same param count with method-2 , while its first param type is String

The main() calls method-1 with a parameter of type String , in the body of method-1 it calls another method, which one is matched, method-2 or method-3 ?

I test it in java 8, the out put is

1.....2.....3.....

Overload is decided at compile-time , so when the first method gets the abc parameter it sees it as an Object (not a String ) and calls method-2 which has the appropriate signature for it.

You are probably confused because this is different from the dynamic linking mechanism, which applies to class instances (objects) methods, and resolves the method at runtime based on the actual class of the instance on which the call is made (for example toString() in abc.toString() ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM