Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Method overloading

Explains Java method overloading: definition, signature rules, overload resolution order (exact, widening, boxing/unboxing, varargs), ambiguity cases, and interactions with inheritance, with runnable examples.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Method overloading lets you define multiple methods with the same name but different parameter lists to handle different types and counts of inputs. Engineers use it to design clean, readable APIs (for example, multiple constructors or utility methods that accept int, long, double, String, or arrays) without inventing many method names.

Key ideas

  • Definition: A method signature (in Java) is the method’s name and the ordered list of parameter types. It does not include the return type, access modifier, throws clause, or parameter names.
  • Definition: Method overloading is having two or more methods in the same class (or inherited into it) with the same name but different parameter lists (different number of parameters, or at least one different parameter type, or different parameter order when types differ).
  • Exact statement (rule): Two methods cannot be overloaded by changing only the return type, only the access modifier, only the throws list, or only parameter names. At least the parameter types or their count must differ.
  • Definition: Overload resolution is the compile-time process by which the compiler chooses which overloaded method to call based on the method name and the compile-time types of the arguments.
  • Definition: Applicable method is an overload for which each argument can be converted to the corresponding parameter type using allowed method invocation conversions (explained below).
  • Definition: Most specific method is the applicable method whose parameter types are more specific (subtypes or narrower primitives) than the others for the given arguments. If there is a tie, the call is ambiguous and results in a compile-time error.
  • Definition: Primitive widening is conversion from a smaller primitive type to a larger compatible primitive type (e.g., byte→short→int→long→float→double, and char→int→long→float→double). Primitive narrowing (e.g., long→int) is not applied automatically in overload resolution.
  • Definition: Boxing wraps a primitive value into its wrapper class (e.g., int→Integer). Unboxing extracts the primitive from its wrapper (e.g., Integer→int). These are automatic since Java 5.
  • Definition: Varargs (variable arity) allows a method to accept zero or more arguments of a type using the ... syntax (e.g., int...). It is compiled as an array parameter. Also: Only one varargs parameter is allowed and it must be last.
  • Law-like ordering for overload resolution (at a high level, for a single method name and arity being considered):
    1. Prefer an exact match without conversion if available.
    2. If no exact match, prefer methods using primitive widening over those requiring boxing/unboxing.
    3. Prefer methods using boxing/unboxing over those requiring varargs.
    4. If multiple methods are still applicable, choose the most specific parameter types. If no unique most specific method exists, the call is ambiguous (compile-time error). Assumptions: All candidate methods are accessible; generic inference (if any) succeeds; there is no primitive narrowing required; and we consider fixed-arity applicability before varargs applicability.
  • Statement: Passing null selects the most specific reference-type overload (e.g., among m(Object) and m(String), m(String) is chosen). If two unrelated reference types are both applicable (e.g., m(String) and m(StringBuilder)), and neither is a subtype of the other, the call with null is ambiguous.
  • Statement: Varargs are considered only after fixed-arity overloads. Among fixed-arity candidates, choose the most specific as above; if none, a varargs method may be chosen.
  • Statement: Overloading vs overriding:
    • Overloading is compile-time selection among methods with the same name but different parameter lists. It depends on the compile-time types of arguments and the reference variable.
    • Overriding is runtime selection of which implementation to execute when a subclass replaces a superclass method with the same signature (name + parameter types). It depends on the actual object’s runtime type. Typical exam contrast: Overloading = compile-time polymorphism; Overriding = runtime polymorphism (dynamic binding). Return type can differ in overriding only if covariant (a subtype of the original return type), but that is outside pure overloading.
  • Statement: Overloading with inheritance:
    • Overloads in a subclass are considered for resolution only if the compile-time type of the reference can see them. If a variable is declared as the superclass type, overload resolution considers only methods available in that superclass type (including overridden versions), not new overloads declared only in the subclass.
  • Statement: Arrays and varargs: T... is compiled as T[]. You cannot have two overloads that differ only by T[] vs T... because they have the same signature after compilation.
  • Statement: Generic methods and overloading: Two methods that become identical after type erasure (same name and same parameter types after removing generics) cannot both exist; this is a duplicate method error.

Diagram to draw in exams (describe):

  • Draw a flowchart titled “Overload Resolution”.
    • Box 1: “Collect candidate methods with the same name in the type hierarchy (and accessible).”
    • Arrow to Box 2: “Filter applicable methods (can convert each argument using method invocation conversions).”
    • Arrow to Decision Diamond A: “Any fixed-arity applicable methods?” Yes/No.
      • If Yes: “Select most specific among fixed-arity methods (prefer exact, then primitive widening, then boxing/unboxing). If tie → Ambiguity (compile-time error).”
      • If No: “Consider varargs methods; form an array if needed. Select the most specific varargs method. If tie → Ambiguity.”
    • End: “Chosen method at compile time.” Add a note: “If overridden, runtime selects implementation based on actual object.”

Formulas

modifier(s) returnType methodName(parameterType1 p1, parameterType2 p2, ...) [throws ExceptionType] { ... }

  • Overloaded methods must differ by parameter list: void m(int a) and void m(long a) and void m(int a, int b) are valid overloads.
  • Not valid (only return type differs): int m(int a) and long m(int a) // compile-time error: duplicate method
  • Varargs syntax: void m(int... values) // zero or more int arguments; inside, values is an int[]
  • Boxing and unboxing types: int ↔ Integer, long ↔ Long, double ↔ Double, boolean ↔ Boolean, char ↔ Character, byte ↔ Byte, short ↔ Short, float ↔ Float
  • Ambiguity with null: void m(String s) and void m(StringBuilder sb) → m(null) is ambiguous
  • Overloading vs overriding quick rule: Overloading → compile-time; Overriding → runtime (dynamic binding)

Worked examples

Example 1: Basic overloading, widening, boxing, and varargs ordering

public class OverloadBasics {
    static void pick(int x) {
        System.out.println("int");
    }
    static void pick(long x) {
        System.out.println("long");
    }
    static void pick(Integer x) {
        System.out.println("Integer");
    }
    static void pick(int... xs) {
        System.out.println("int varargs length=" + xs.length);
    }

    public static void main(String[] args) {
        pick(5);                 // exact match: int
        pick(5L);                // exact match: long
        pick((short) 5);         // primitive widening: short → int
        Byte b = 5;              // constant-in-range narrowing int→byte, then boxing to Byte; later unboxing + widen to int for pick(int)
        pick(b);                 // unbox Byte → byte, then widen byte → int
        pick();                  // varargs with zero args → int[] of length 0
        pick(1, 2, 3);           // varargs with three ints
    }
}

Sample input: (No input)

Exact output:

int
long
int
int
int varargs length=0
int varargs length=3

Explanation highlights:

  • 5 chooses pick(int).
  • (short)5 widens to int (no narrowing allowed, so int beats long; int is more specific).
  • Byte b chooses pick(int) via unboxing then widening.
  • Varargs is used only when no fixed-arity method matches the given number of arguments.

Example 2: Ambiguity with null, boxing vs varargs, and resolving by cast

public class AmbiguityDemo {
    static void show(Integer x) {
        System.out.println("Integer");
    }
    static void show(Object x) {
        System.out.println("Object");
    }
    // Note: Including both of the next two methods would cause ambiguity for null.
    // We include only one pair to keep the program runnable and then demonstrate casts.
    static void demoBoxingVsVarargs() {
        // Overloads in this class: show(Integer) and show(Object)
        // Add a separate varargs overload in an inner helper to illustrate preference.
        Helper.show(5);          // boxing to Integer is preferred over varargs
        Helper.show(1, 2, 3);    // matches varargs directly
    }

    static class Helper {
        static void show(Integer x) {
            System.out.println("Helper: Integer");
        }
        static void show(int... xs) {
            System.out.println("Helper: int varargs length=" + xs.length);
        }
    }

    public static void main(String[] args) {
        // Calling show with null: chooses the most specific reference type.
        show((Integer) null);    // picks Integer
        show((Object) null);     // picks Object by explicit cast

        // Illustrate the ambiguous case using casts with two unrelated reference types.
        // Suppose there were overloads: m(String) and m(StringBuilder). Then m(null) is ambiguous.
        // We demonstrate by explicit casts on a single method name:
        pick((String) null);         // chooses String version
        pick((StringBuilder) null);  // chooses StringBuilder version

        demoBoxingVsVarargs();
    }

    static void pick(String s) {
        System.out.println("String");
    }
    static void pick(StringBuilder sb) {
        System.out.println("StringBuilder");
    }
}

Sample input: (No input)

Exact output:

Integer
Object
String
StringBuilder
Helper: Integer
Helper: int varargs length=3

Explanation highlights:

  • With both show(Integer) and show(Object), a null literal could go to either; the most specific is Integer, but here we used explicit casts to demonstrate both choices safely.
  • For Helper.show, 5 prefers boxing to Integer over using varargs (fixed-arity preferred over varargs), and multiple ints choose varargs.
  • Between pick(String) and pick(StringBuilder), a plain pick(null) would be ambiguous; explicit casts resolve it.

Example 3: Overloading vs overriding with inheritance

class Parent {
    void show(Object o) {
        System.out.println("Parent.show(Object)");
    }
    void show(Number n) {
        System.out.println("Parent.show(Number)");
    }
}

class Child extends Parent {
    // Override of show(Number)
    @Override
    void show(Number n) {
        System.out.println("Child.show(Number)");
    }
    // New overload only in Child
    void show(Integer i) {
        System.out.println("Child.show(Integer)");
    }
}

public class OverloadOverrideTest {
    public static void main(String[] args) {
        Parent pRef = new Child();
        Number n = Integer.valueOf(10);
        pRef.show(n);                 // Overload resolution uses Parent's methods; override picked at runtime
        pRef.show(Integer.valueOf(20)); // Still resolves to Parent.show(Number) at compile time; overridden in Child

        Child cRef = new Child();
        cRef.show(Integer.valueOf(30)); // Overload resolution sees Child.show(Integer) and picks it
        cRef.show(40);                  // int autoboxes to Integer; picks Child.show(Integer)
        cRef.show(40L);                 // long autoboxes to Long; best is Parent.show(Number) overridden to Child.show(Number)
    }
}

Sample input: (No input)

Exact output:

Child.show(Number)
Child.show(Number)
Child.show(Integer)
Child.show(Integer)
Child.show(Number)

Explanation highlights:

  • pRef has compile-time type Parent, so overload resolution only considers Parent’s visible methods. The call binds to show(Number) at compile time, and the overridden Child.show(Number) runs at runtime.
  • cRef has compile-time type Child, so the Child-only overload show(Integer) can be selected.
  • int → Integer and long → Long via boxing; Integer and Long are both subtypes of Number, so calls may select the most specific overload available in the reference type.

Common mistakes

  • Expecting primitive narrowing (e.g., long to int) to happen automatically in overload resolution. It does not; you must cast, or choose a wider parameter.
  • Forgetting the precedence: exact match > primitive widening > boxing/unboxing > varargs. Writing answers that reverse “boxing vs varargs” or “widening vs boxing”.
  • Assuming overloading is decided at runtime like overriding. Overloading is compile-time; the declared type of the reference matters.
  • Calling an overloaded method with null when multiple unrelated reference types are candidates (e.g., String vs StringBuilder), causing an ambiguous call.
  • Assuming varargs and arrays are different signatures for overloading. They are the same after compilation; you cannot overload with int[] and int... only.
  • Forgetting that fixed-arity overloads are preferred over varargs; surprised when a boxing overload wins over a varargs one.
  • Overloading methods in a subclass and expecting them to be considered when a variable is typed as the superclass. Overload resolution uses the compile-time type, not the runtime object.

For your exam

  • Short notes: Order of overload resolution (exact, widening, boxing, varargs) with one or two examples. Ambiguity with null and how to resolve it using casts. Effect of varargs and when it is considered.
  • Explain with diagrams: Draw the overload resolution flowchart as described (collect candidates → filter applicable → fixed-arity preference → most specific → ambiguity).
  • Programs: Write a small Java program showing which overload is chosen for different arguments, including a case with Byte/Integer, a varargs case, and a widening vs boxing demonstration. Include expected output and explain lines briefly.
  • Theory compare/contrast: Overloading vs overriding (compile-time vs runtime). Explain how inheritance interacts: the compile-time type of the reference controls overload selection; overriding changes the implementation at runtime.
  • Tricky cases: Ambiguity with null; no primitive narrowing; generics erasure causing duplicate method errors if two generic overloads erase to the same signature.
  • To score full marks: Use correct terminology, state the precedence order, show at least one unambiguous example and one ambiguous case with resolution, and clearly distinguish overloading from overriding.

Quick check

  1. Given overloads: void f(long), void f(Integer), and the call f(5), which method is chosen and why?
  2. Why is a call g(null) ambiguous if both g(String) and g(StringBuilder) exist?
  3. In class B extends A, A has void h(Number), B adds void h(Integer), and variable A a = new B(); What prints for a.h(Integer.valueOf(7)) if both methods print their names?

Answers: 1) f(long) — because primitive widening (int→long) is preferred over boxing (int→Integer). 2) Because null can match both reference parameters and neither String nor StringBuilder is more specific than the other, so no unique most specific method exists. 3) The call resolves at compile time to h(Number) (only A’s overloads are considered), and at runtime the overridden version (if overridden in B) runs; output is B’s implementation of h(Number) if it overrides A.h(Number).

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?