Java 5: Methods, Overloading & the main Signature
easy⏱ 5 mincoursejava
Overloading = static, Overriding = dynamic
Overloading picks a method by the compile-time types of arguments — identical within a single class. Overriding replaces a superclass method with a subclass version of the same signature, chosen at runtime by the actual object type. A child class method with a different parameter list isn't an override — it's an overload, and the parent method still exists.
class Printer {
void print(Object o) { System.out.println("Object"); }
void print(String s) { System.out.println("String"); }
}
Object x = "hello"; // runtime: String, compile-time: Object
new Printer().print(x); // prints "Object" — overload resolved at compile time
Resolution rules in order
When multiple overloads match, Java picks the most specific one in this order: (1) exact match, (2) widening conversion (int -> long), (3) autoboxing (int -> Integer), (4) varargs. Mixing these is a common gotcha — call(1) where you have call(long) and call(Integer) picks call(long) because widening beats boxing.
static void call(long n) { System.out.println("long"); }
static void call(Integer n) { System.out.println("Integer"); }
static void call(int... n) { System.out.println("varargs"); }
call(1); // prints "long" — widening int->long beats boxing int->Integer
The main signature
Any of these are valid entry points: public static void main(String[] args), public static void main(String... args) (varargs is just an array), static public void main(...) (modifier order doesn't matter). main must be static (no instance yet) and return void. Java 21 preview: unnamed classes and instance main methods.
Build a dispatch tracer
Write dispatch(declared, runtime) that takes a 'declared type' name and simulates which overload wins. Given overloads for Object, CharSequence, and String, show that a String passed as Object picks the Object overload — and as CharSequence picks CharSequence. Overloading is decided before the JVM sees the real object.
Avoid overloading ambiguity
Overloads that differ only by a parameter's superclass/subclass relationship invite bugs. Prefer distinct method names (printObject, printString) or distinct method count/kinds. Effective Java Item 52 goes further: avoid overloading with the same number of parameters where possible.
Quiz: The @Override trap
What does @Override do at compile time? It forces a compile error if the method doesn't actually override a parent method. Without it, a typo (equals(Object o) vs equls(Object o)) silently becomes an overload instead of an override — one of the most common subtle Java bugs. Always use @Override.