• ↑↓ pour naviguer
  • pour ouvrir
  • pour sélectionner
  • ⌘ ⌥ ↵ pour ouvrir dans un panneau
  • ←→ pour naviguer
  • esc pour rejeter
⌘ '
raccourcis clavier

The Problem

A class often needs multiple versions of the same operation that differ only in their inputs. A print() method should work with integers, strings, and booleans. Without overloading, each variant would need a distinct method name (printInt, printString, printBool), making the API inconsistent and hard to remember.

Core Idea

Compile-time Polymorphism (also called Method Overloading) allows multiple methods in the same class to share the same name but have different parameter lists. The compiler determines which version to call based on the number, type, and order of arguments. This decision is made at compile time — hence the name. Overloading improves code readability by using consistent names for logically similar operations.

How It Works

The compiler uses the method signature (name + parameter types) to select the correct overload. It applies widening conversions, autoboxing, and varargs in that order of preference. If no matching overload is found, a compile error occurs. Overloaded methods can differ in parameter count, parameter types, or both. Return type alone is NOT sufficient for overloading — the compiler needs parameter differences.

Visual Explanation

compile_time_polymorphism Call add(2, 3) add(2, 3, 4) add(2.5, 3.5) Compiler Compiler (Compile Time) Call->Compiler Resolved1 add(int a, int b) → returns 5 Compiler->Resolved1 match: 2 ints Resolved2 add(int a, int b, int c) → returns 9 Compiler->Resolved2 match: 3 ints Resolved3 add(double a, double b) → returns 6.0 Compiler->Resolved3 match: 2 doubles

Semantic Network

semantic_compile_time_poly THIS Compile-Time Poly POLY Polymorphism THIS--POLY built from METHODS Methods THIS--METHODS builds into RUNTIME Runtime Poly THIS--RUNTIME contrasts with

Key Properties

  • Same name, different parameters: Number, type, or order of parameters must differ
  • Compile-time resolution: Which method to call is decided when code is compiled
  • Return type alone is insufficient: Methods differing only in return type cause compile error
  • Widening preferred over boxing: Java prefers widening (int → double) over autoboxing (int → Integer)
  • Varargs is last resort: If no exact match is found, varargs is used as fallback

Connections

Edge Cases & Gotchas

  • Ambiguous call: If two overloads are equally applicable (e.g., method(Integer) and method(String) with null), the compiler reports ambiguity
  • Widening + boxing chain: Widening followed by boxing is not supported — int cannot widen then autobox to Long
  • Varargs ambiguity: Overloading with varargs can create ambiguous calls — the compiler cannot distinguish method(int...) from method(Integer...) with null