Which Overloaded Method is Called in Java

后端 未结 5 567
一向
一向 2021-01-30 12:56

I have a basic inheritance situation with an overloaded method in the super class.

public class Person {
    private String name;
    private int dob;
    priva         


        
5条回答
  •  孤独总比滥情好
    2021-01-30 13:10

    Call preference

    class Foo {
        static void test(int arg) { System.out.println("int"); }
        static void test(float arg) { System.out.println("float"); }
        static void test(Integer arg) { System.out.println("Integer"); }
        static void test(int... arg) { System.out.println("int..."); }
    
        public static void main(String[] arg) {
            test(6);
        }
    }
    

    The output will be int printed on console. Now you comment the first test() method and see what is the output coming.

    This is the preference hirarchey in primitive data types. Now coming to derived types declare a class FooChild like this

    class FooChild extends Foo {
    
    }
    

    and create two new methods in Foo like

    static void testChild(Foo foo) { System.out.println("Foo"); }
    static void testChild(FooChild fooChild) { System.out.println("FooChild"); }
    

    then in main method try calling testChild like this testChild(new FooChild());.

提交回复
热议问题