Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Method picking algorithm [duplicate]

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.

like image 348
Philipp B. Avatar asked Dec 14 '22 16:12

Philipp B.


2 Answers

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.

like image 107
Binkan Salaryman Avatar answered Dec 31 '22 14:12

Binkan Salaryman


Java will choose the most specific of the two methods provided (See the Java Language Specification)

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

As the class hierarchy for Frame is

java.lang.Object
    java.awt.Component
        java.awt.Container
            java.awt.Window
                java.awt.Frame

An the class hierarchy for Window is

java.lang.Object
    java.awt.Component
        java.awt.Container
            java.awt.Window

Frame is the most specific method, and then, your public static void hello(Frame f) will be chosen.

like image 36
antonio Avatar answered Dec 31 '22 13:12

antonio