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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With