The Most Specific Method Rule
You'll learn: How Java's compiler chooses between multiple overloaded methods when more than one could match your call.
Why This Matters
When you overload methods, you might call them with arguments that could match several different parameter types. Java needs a systematic way to pick the best one — and it always chooses the most specific match.
The Core Idea
When the compiler sees a method call, it looks at all overloaded versions and asks: "Which parameter types are the closest match to what the programmer passed?"
More specific means:
- An exact type match beats a widened type
- A narrower type beats a wider type
intis more specific thanlong, which is more specific thandouble
public static void display(int x) {
System.out.println("int version: " + x);
}
public static void display(double x) {
System.out.println("double version: " + x);
}
public static void main(String[] args) {
display(10); // Calls int version (exact match)
display(10.5); // Calls double version (exact match)
byte b = 5;
display(b); // Calls int version (byte widens to int, not double)
}
The compiler picks display(int) for the byte because byte → int is a smaller conversion than byte → double. The int method is more specific.
Analogy
Imagine asking for a "small coffee." If the shop has "small," "medium," and "large," they give you the small — the most specific match. They don't give you medium just because small could fit into it.
Key Takeaway: Java always selects the overloaded method whose parameter types require the least widening from the argument types — the most specific applicable method wins.