javamethods

Java - Method picking algorithm


I was messing around with methods and was looking, which Method will be executed if I make two Methods named "hello", with different objects they want and pass a "null" to the method:

    public static void main(String... args) {
        hello(null);
    }

    public static void hello(Window w) {
        System.out.println("Hello");
    }

    public static void hello(Frame f) {
        System.out.println("Bye");
    }

The output was every time "Bye", but I still don't understand the logic behind that. After a short research with google, without of any explanation, I decided to ask the question here.

I hope that someone can explain the selection algorithm or give me a link to a explanation.


Solution

  • The compiler prefers the most specialized type:

    public class Parent {
        public static void main(String... args) {
            hello(null); // takes `Child`
        }
    
        public static void hello(Parent _) {
            System.out.println("SuperClass");
        }
    
        public static void hello(Child _) {
            System.out.println("SubClass");
        }
    }
    
    class Child extends Parent {
    
    }
    

    For the reason, take a look at this thread, @Hayden already mentioned in his comment.