JAVA BASICS IN DETAIL

Java method overloading

Method overloading ( method overloading) lets a class define multiple methods with the same name and different parameter lists. The same clearly named action can work with different numbers or types of arguments.

A simple example: different parameter counts

class Skaiciuotuvas {
    int sudeti(int pirmas, int antras) {
        return pirmas + antras;
    }

    int sudeti(int pirmas, int antras, int trecias) {
        return pirmas + antras + trecias;
    }
}

Skaiciuotuvas skaiciuotuvas = new Skaiciuotuvas();

System.out.println(skaiciuotuvas.sudeti(4, 6));
System.out.println(skaiciuotuvas.sudeti(4, 6, 5));
Console output

10
15

  1. Both methods are named sudetibecause they perform the same action.
  2. The first accepts two int parameters, matching the call sudeti(4, 6).
  3. The second accepts three parameters, matching the call sudeti(4, 6, 5).
  4. The compiler selects the appropriate method before the program runs.

Different parameter types

class KainosSpausdintuvas {
    void rodyti(int eurai) {
        System.out.println("Kaina: " + eurai + " Eur");
    }

    void rodyti(double eurai) {
        System.out.printf("Kaina: %.2f Eur%n", eurai);
    }
}

KainosSpausdintuvas spausdintuvas = new KainosSpausdintuvas();
spausdintuvas.rodyti(12);
spausdintuvas.rodyti(12.5);
Console output

Kaina: 12 Eur
Kaina: 12.50 Eur

  1. For the integer 12 , the exact match is the method with an int parameter.
  2. The value 12.5 needs the method with a double parameter.
  3. The methods can contain different code, but their shared name expresses the same purpose: displaying a price.

Different parameter order

class Pristatymas {
    void registruoti(String miestas, int pastoKodas) {
        System.out.println(miestas + ", " + pastoKodas);
    }

    void registruoti(int pastoKodas, String miestas) {
        System.out.println(pastoKodas + ", " + miestas);
    }
}

Pristatymas pristatymas = new Pristatymas();
pristatymas.registruoti("Kaunas", 44280);
pristatymas.registruoti(92118, "Klaipėda");
Console output

Kaunas, 44280
92118, Klaipėda

The signatures registruoti(String, int) and registruoti(int, String) are different, so Java permits them. However, such similar variants can confuse people. If the arguments' meaning is unclear from the call, distinct, clearer method names are preferable.

What makes up a method signature?

What allows method overloading?
UpdateDoes it create another overload?Why?
Parameter countYesCalls have different argument counts
Parameter typesYesThe compiler can select based on argument types
Parameter type orderYesProduces a different parameter list
Parameter namesNoNames are not part of the method signature
Return typeNoJava cannot choose a method based only on the expected result
Access modifierNopublic or private does not change the method signature

The closest match and numeric widening

class Matavimas {
    void rodyti(int reiksme) {
        System.out.println("int: " + reiksme);
    }

    void rodyti(double reiksme) {
        System.out.println("double: " + reiksme);
    }
}

Matavimas matavimas = new Matavimas();
short trumpasSkaicius = 7;

matavimas.rodyti(5);
matavimas.rodyti(5.5);
matavimas.rodyti(trumpasSkaicius);
Console output

int: 5
double: 5.5
int: 7

  1. 5 is int, so the exact match is selected.
  2. 5.5 is double, so the second method is selected.
  3. short variant is unavailable, so Java safely widens short to int.
  4. If several options are possible, the compiler seeks the most specific applicable match.

An ambiguous call

class Pastaba {
    void issaugoti(String tekstas) { }
    void issaugoti(StringBuilder tekstas) { }
}

Pastaba pastaba = new Pastaba();

// Error: null matches both methods
pastaba.issaugoti(null);
Result

The code does not compile: null can be either a Stringand StringBuilder reference, and neither type is clearly more appropriate here.

Too many similar overloads make an API harder to use. A method API should be easy to understand, as well as technically valid.

Static methods can also be overloaded

class Tekstas {
    static String sujungti(String pirmas, String antras) {
        return pirmas + " " + antras;
    }

    static String sujungti(String pirmas, String antras, String trecias) {
        return pirmas + " " + antras + " " + trecias;
    }
}

System.out.println(Tekstas.sujungti("Labas", "Ieva"));
System.out.println(Tekstas.sujungti("Gražios", "tau", "dienos"));
Console output

Labas Ieva
Gražios tau dienos

Overloading applies to both instance and static methods. Methods with the same name must have different parameter lists.

Why is it called compile-time polymorphism?

The compiler can determine from the arguments which overloaded method to call. The choice is not deferred until runtime. Method overloading is therefore also called static or compile-time polymorphism.

Do not confuse this with method overriding.

Overloading means multiple methods with the same name and different parameters. Overriding (overriding) happens in inheritance when a subclass supplies its own implementation of an inherited method.

Method and constructor overloading

Comparing the two kinds of overloading
PropertyMethod overloadingConstructor overloading
PurposePerform a similar action with different dataCreate an object in different ways
NameThe same method nameAlways the class name
Return typePresent, but does not determine overloadingNot written
InvocationThrough an object or class if the method is staticUsually with new

More about Java constructor overloading

What should you remember?

  • Overloaded methods have the same name and different parameter lists.
  • You can change the parameter count, types or order.
  • Parameter names and the return type do not create an overload.
  • The compiler chooses the closest applicable match.
  • Java can perform safe primitive widening if no exact variant exists.
  • Avoid overloads that people or the compiler can easily confuse.