0% found this document useful (0 votes)
2 views23 pages

Method Overloading Complete Notes

The document provides comprehensive notes on method overloading and compile-time polymorphism in Java, using a calculator application as an example. It explains the concept of method overloading, how the Java compiler resolves overloaded methods through specific rules, and discusses type promotion and ambiguity in method calls. The notes also include code examples and best practices for understanding and implementing method overloading effectively.

Uploaded by

gobinisharavi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views23 pages

Method Overloading Complete Notes

The document provides comprehensive notes on method overloading and compile-time polymorphism in Java, using a calculator application as an example. It explains the concept of method overloading, how the Java compiler resolves overloaded methods through specific rules, and discusses type promotion and ambiguity in method calls. The notes also include code examples and best practices for understanding and implementing method overloading effectively.

Uploaded by

gobinisharavi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JAVA PROGRAMMING

Complete Class Notes


Topic: Method Overloading & Compile-Time Polymorphism

LiveWire — Full Stack Java Certification


Table of Contents
• 1. Introduction — The Calculator Problem
• 2. The Problem with Multiple Method Names
• 3. What is Method Overloading?
• 4. Complete Calculator Code (with Method Overloading)
• 5. How Does Java Compiler Resolve Method Overloading? (3 Rules)
• 6. Type Promotion
• 7. Ambiguity in Method Overloading
• 8. Why is it Called Compile-Time Polymorphism?
• 9. What is True vs False Polymorphism?
• 10. All Names for Method Overloading
• 11. Real-World Examples of Method Overloading in Java
• 12. How to Answer Method Overloading in an Interview
• 13. Quick-Reference Summary Table
• 14. Interview Q&A
1. Introduction — The Calculator Problem
Java is an Object-Oriented Programming (OOP) language. To write any application, you always start by
creating a class. In this session, we build a Calculator application step by step to understand method
overloading.

1.1 Setting Up the Calculator Class


Since Java is OOP, the very first thing we do is create a class. We name it Calculator01.
// Step 1: Create the class
class Calculator01 {
// Methods will go inside here
}

A class is like a blueprint — it is imaginary. An object is the real thing created from that blueprint.

1.2 Creating the First Method — add1


We write our first method called add1 that takes two integer parameters and prints their sum.
public class Calculator01 {

// Method 1: Add two integers


public void add1(int a, int b) {
int c = a + b; // add a and b, store in c
[Link](c); // print the result
}
}

Line-by-line explanation:
• public — access modifier; method is accessible from anywhere
• void — return type; the method does NOT return a value, it only prints
• add1 — name of the method
• int a, int b — two parameters of type integer accepted by the method
• int c = a + b; — declares an integer variable c and stores the sum of a and b
• [Link](c); — prints the value of c to the console

2. The Problem with Multiple Method Names


A real calculator must be able to add numbers of different data types — int, float, long, double, short,
and combinations of them. So the trainer created 8 separate methods named add1 through add8, each
handling a different combination of data types.
2.1 The Eight Methods (Before Overloading)
public class Calculator01 {

// add1: two integers


public void add1(int a, int b) {
int c = a + b;
[Link](c);
}

// add2: two floats


public void add2(float a, float b) {
float c = a + b; // float + float = float
[Link](c);
}

// add3: two longs


public void add3(long a, long b) {
long c = a + b; // long + long = long
[Link](c);
}

// add4: int + float


public void add4(int a, float b) {
float c = a + b; // int + float = float (higher type wins)
[Link](c);
}

// add5: three integers


public void add5(int a, int b, int c) {
int sum = a + b + c;
[Link](sum);
}

// add6: two longs + one int


public void add6(long a, long b, int c) {
long sum = a + b + c; // long wins
[Link](sum);
}

// add7: two floats + one int (float wins)


public void add7(float a, float b, int c) {
float sum = a + b + c;
[Link](sum);
}

// add8: short + int + float (float wins)


public void add8(short a, int b, float c) {
float sum = a + b + c;
[Link](sum);
}
}

Data Type Hierarchy (Higher wins in arithmetic)


byte < short < int < long < float < double
When two different types are involved in an operation, the result is always of the HIGHER data
type.
Examples: int + float = float | long + long = long | short + int = int
2.2 Creating an Object and Calling Methods
A class is just a blueprint. To actually run the code, you need to create an object.
public class Calculator01 {

// ... (all the add methods above)

public static void main(String[] args) {

// Create an object of Calculator01


Calculator01 calc = new Calculator01();

// Call add1 — adds two integers


calc.add1(10, 20); // Output: 30

// Call add3 — adds two long values (L suffix needed)


calc.add3(100L, 200L); // Output: 300

// Call add8 — short + int + float


calc.add8((short)2, 5, 3.5f);
}
}

Important syntax notes:


• new Calculator01() — creates an object in memory
• calc — reference variable pointing to the object
• 100L — the L suffix tells Java this literal is a long value
• 3.5f — the f suffix tells Java this literal is a float (without f, Java treats 3.5 as double)

2.3 The Core Problem — What's Wrong With add1, add2 … add8?
You only wrote this code — and already you can't remember which method does what! Now imagine
building an entire enterprise application with hundreds of methods. The same problem early software
developers faced:
• They invested time memorizing method names instead of building new features.
• Documentation became massive: 'add1 = two integers, add2 = two floats…'
• Code became error-prone because developers called the wrong method.

Key insight: All 8 methods are doing the same job — adding numbers. Why do they need 8 different
names?
3. What is Method Overloading?

METHOD OVERLOADING
Method Overloading is the process of creating multiple methods with the SAME NAME
within the SAME CLASS, where each method has a different number or type of parameters.
The Java compiler decides at compile time which method to call.

⚠️CRITICAL — Never forget 'within the same class'


Most students say: 'Multiple methods with the same name' — this is WRONG / INCOMPLETE.
Correct definition: 'Multiple methods with the same name WITHIN THE SAME CLASS'.
Omitting 'within the same class' makes your definition completely wrong in an interview.

3.1 The Solution — Rename All Methods to 'add'


Instead of add1, add2 … add8, we rename every single method to just add. Now a developer only
needs to remember ONE name: add.
// Now ALL eight methods are named 'add'
// The difference is in the PARAMETERS, not the name

public void add(int a, int b) { ... } // version 1


public void add(float a, float b) { ... } // version 2
public void add(long a, long b) { ... } // version 3
public void add(int a, float b) { ... } // version 4
public void add(int a, int b, int c) { ... } // version 5
public void add(long a, long b, int c) { ... } // version 6
public void add(float a, float b, int c) { ... }// version 7
public void add(short a, int b, float c) { ... }// version 8

Now calling the method is extremely simple:


[Link](25.5f, 2.58f); // Java calls version 2 (float, float)
[Link](100L, 200L); // Java calls version 3 (long, long)
[Link](10, 20); // Java calls version 1 (int, int)
[Link](5, 3, 8); // Java calls version 5 (int, int, int)

You don't have to remember which version to call. Just pass the values — Java figures it out!
4. Complete Calculator Class with Method Overloading

public class Calculator01 {

// Method 1: Two integers


public void add(int a, int b) {
int c = a + b;
[Link](c);
}

// Method 2: Two floats


public void add(float a, float b) {
float c = a + b;
[Link](c);
}

// Method 3: Two longs


public void add(long a, long b) {
long c = a + b;
[Link](c);
}

// Method 4: int and float


public void add(int a, float b) {
float c = a + b;
[Link](c);
}

// Method 5: Three integers


public void add(int a, int b, int c) {
int sum = a + b + c;
[Link](sum);
}

// Method 6: Two longs + one int


public void add(long a, long b, int c) {
long sum = a + b + c;
[Link](sum);
}

// Method 7: Two floats + one int


public void add(float a, float b, int c) {
float sum = a + b + c;
[Link](sum);
}

// Method 8: short + int + float


public void add(short a, int b, float c) {
float sum = a + b + c;
[Link](sum);
}

public static void main(String[] args) {


Calculator01 calc = new Calculator01();

[Link](10, 20); // Calls Method 1 → Output: 30


[Link](25.5f, 2.58f); // Calls Method 2 → Output: 28.08
[Link](100L, 200L); // Calls Method 3 → Output: 300
[Link](10, 5.5f); // Calls Method 4 → Output: 15.5
[Link](1, 2, 3); // Calls Method 5 → Output: 6
}
}
5. How Does Java Compiler Resolve Method Overloading?

The 3 Rules of Method Overloading


When you call an overloaded method, the Java Compiler (NOT the JVM) decides which version to
execute. It follows exactly 3 rules in sequence:

Rule 1: Method Name Check


1 The compiler first looks for ALL methods in the class that have the SAME NAME as the
one being called. All matching methods are considered as candidates.

Rule 2: Number of Parameters


2 Among the candidates from Rule 1, the compiler now keeps only those methods that
match the EXACT NUMBER of arguments you passed in the method call.

Rule 3: Type of Parameters


Among remaining candidates, the compiler checks the DATA TYPE of each parameter in
3 order. The method whose parameter types exactly match the passed argument types is
selected.

5.1 Step-by-Step Trace Example


Let's trace: [Link](100L, 200L) — two long values.
Rule 1 — Check method name 'add':
→ All 8 methods named 'add' are candidates. All 8 stand up.

Rule 2 — Check number of parameters (2 passed):


→ Methods 1, 2, 3, 4 have 2 parameters → still standing (4 methods)
→ Methods 5, 6, 7, 8 have 3 parameters → they sit down

Rule 3 — Check type of parameters (long, long):


→ add(int, int) → types don't match → sits down
→ add(float, float) → types don't match → sits down
→ add(long, long) → MATCH! → this method is called ✓
→ add(int, float) → types don't match → sits down

Result: add(long a, long b) is executed!

Who does Method Overloading?


It is the JAVA COMPILER — NOT the JVM.
Method overloading is resolved at COMPILE TIME (before the program runs).
This is why it is called Compile-Time Polymorphism.
Proof: If you call add(2.5, 3.5) — double, double — and no such method exists,
Java shows a RED ERROR LINE immediately in the editor, even before you run the
program.
5.2 The Classroom Analogy (Ramu)
The trainer explained this with a brilliant analogy:
• Imagine you have 10 office boys — all named 'Ramu'.
• When you call 'Ramu', ALL 10 respond at first (Rule 1 — method name).
• You say 'Ramu, bring water for 1 table' — those assigned more tasks sit down (Rule 2 —
parameter count).
• You then say the specific type of task — only the Ramu with that exact duty stays standing
(Rule 3 — parameter type).
• From a visitor's perspective, it looks like ONE Ramu is doing everything — but in reality, there
are 10 different people, each with a different job.
• This illusion of 'one person, many jobs' is POLYMORPHISM.
6. Type Promotion in Method Overloading

TYPE PROMOTION
When all 3 rules fail to find an exact match, the Java compiler promotes (widens) the data
type of the passed argument to the next higher compatible type and tries again. This is also
known as implicit type casting or widening conversion.

6.1 Type Promotion Example


Suppose we only have two methods:
public void add(int a, int b) { [Link]("int method"); }
public void add(float a, float b) { [Link]("float method"); }

Now we call:
[Link](100L, 200L); // passing long, long

Compiler checks:
• Rule 1 ✓ — name 'add' matches two methods
• Rule 2 ✓ — both have 2 parameters
• Rule 3 ✗ — no add(long, long) exists!

What Java does next (Type Promotion):


• Can long be promoted to int? NO (long is bigger than int — cannot shrink)
• Can long be promoted to float? YES (float is larger than long)
• → Java promotes long to float and calls add(float, float) successfully.

// Type Promotion Chain:


byte → short → int → long → float → double
char → int

// long cannot go DOWN to int (that would be narrowing — not automatic)


// long CAN go UP to float (widening — automatic / type promotion)

When does Type Promotion happen?


ONLY after all 3 rules fail to find an exact match.
Java finds the closest higher data type and promotes the argument.
This is called Implicit Type Casting or Type Promotion.
The term used in method overloading context is specifically: TYPE PROMOTION.
7. Ambiguity in Method Overloading

AMBIGUITY
Ambiguity occurs when the Java compiler cannot decide WHICH overloaded method to call
because two or more methods are equally valid candidates after type promotion. This results
in a COMPILE-TIME ERROR: 'The method add is ambiguous for the type Calculator01'.

7.1 Ambiguity Example


// We have two overloaded methods:
public void add(int a, float b) {
[Link]("Method 1");
}

public void add(float a, int b) {


[Link]("Method 2");
}

// Now we call with two integers:


[Link](10, 20); // COMPILE ERROR: ambiguous!

Why is it ambiguous?
• Rule 1 ✓ — 'add' matches both methods.
• Rule 2 ✓ — both have 2 parameters.
• Rule 3 ✗ — no exact match for (int, int).
• Type Promotion kicks in:
◦ For Method 1 (int, float): first param int → int (no promotion needed), second param int →
float (possible). Valid.
◦ For Method 2 (float, int): first param int → float (possible), second param int → int (no
promotion needed). Valid.
• BOTH methods are equally valid! Compiler cannot choose. → AMBIGUITY ERROR.

Another Ambiguity Case


Methods: add(int a, float b) and add(long a, int b)
Call: [Link](10, 20) — passing int, int

→ For add(int, float): int→int exact, int→float possible → Valid


→ For add(long, int): int→long possible, int→int exact → Valid

Both equally valid → AMBIGUITY ERROR


The compiler gets confused — just like humans can get confused when two people are equally
qualified.

Fix: Explicitly cast to remove ambiguity:


[Link]((int)10, (float)20); // Clearly calls add(int, float) — Method 1
[Link]((float)10, (int)20); // Clearly calls add(float, int) — Method 2
8. Why is it Called Compile-Time Polymorphism?

8.1 What is Polymorphism?


Poly = Many, Morphism = Forms. Polymorphism means: ONE thing behaving in MANY ways.
Examples from nature:
• Water — same substance, but exists as liquid, solid (ice), and gas (steam)
• Carbon — same element, but forms graphite, coal, and diamond (under pressure)
• A Human Being — same person acting as son/daughter, friend, student, employee, all at once

8.2 Why 'Compile-Time'?


Java program execution has two phases:
1. Compilation Phase — Source code (.java) → Java Compiler → Bytecode (.class)
2. Execution Phase — Bytecode → JVM → Machine Code → Output

Method overloading is resolved DURING THE COMPILATION PHASE by the Java Compiler. The
compiler looks at the method call, applies the 3 rules, and binds the correct method BEFORE the
program even runs. That's why it is called Compile-Time Polymorphism.

Proof that it's Compile-Time:


When you call add(2.5, 3.5) — passing double, double — and no add(double, double) exists,
Java shows a RED error underline in the editor IMMEDIATELY.
You haven't even run the program yet!
This is compile-time detection — the Java Compiler is doing the work.
9. True Polymorphism vs False Polymorphism

FALSE Polymorphism (Method TRUE Polymorphism (Method Overriding)


Overloading)
8 functionalities → 8 methods. Ratio is 8:8 1 method that actually performs differently
based on context. Ratio is 1:many
Looks like one method is doing all the work, ONE method truly behaves differently
but there are actually 8 separate methods depending on the object that calls it
Just an illusion of polymorphism Real, genuine polymorphism
Resolved at Compile Time Resolved at Runtime (Dynamic Dispatch)

The trainer explained using the Ramu analogy: 'If the same Ramu was ACTUALLY capable of doing all
10 different jobs himself — that would be TRUE polymorphism. But in reality there are 10 different
Ramus with the same name doing separate jobs. That illusion is FALSE polymorphism.'
10. All Names for Method Overloading
Method overloading is known by multiple names. In an interview, the question can be asked using ANY
of these terms — they all mean the same thing.

Term Why This Name


Method Overloading You are 'overloading' the method name — same name used by
multiple methods
Compile-Time Polymorphism Resolved at compile time; exhibits the 'many forms' behavior at
compile stage
False Polymorphism Looks like polymorphism (one calling many) but in reality
multiple separate methods exist
Static Binding The binding (linking call to method body) is done statically at
compile time; does not change at runtime
Early Binding Binding happens EARLY — during compilation, before
execution begins

Interview Scenario:
The interviewer may ask:
• 'Explain Method Overloading'
• 'What is Compile-Time Polymorphism?'
• 'What is Static Binding?'
• 'What is Early Binding?'
• 'What is False Polymorphism?'
ALL five questions have the SAME answer. Recognizing this in the interview room is a huge
advantage.
11. Real-World Examples of Method Overloading in Java
The best interview answers include examples that Java itself has built in — overloading you've been
using since Day 1 without realizing it.

11.1 [Link]() — The Most Used Overloaded Method


Every Java program uses println. You've been using overloading from your very first Hello World
program!
// All of these call the SAME NAME 'println' — different types:
[Link](1); // println(int)
[Link]("Hello"); // println(String)
[Link]('A'); // println(char)
[Link](25.5); // println(double)
[Link](25.5f); // println(float)
[Link](true); // println(boolean)
[Link](100L); // println(long)

Inside the PrintStream class, Java has created separate println methods for each data type. When you
write [Link](), the compiler checks the type you pass and calls the correct version.

11.2 [Link]() — Two Overloaded Versions


String s = "Java";

// Version 1: One parameter — start index only


String result1 = [Link](2); // "va" (from index 2 to end)

// Version 2: Two parameters — start and end index


String result2 = [Link](1, 3); // "av" (from index 1 to index 3,
exclusive)

substring is overloaded — one version takes one parameter (start), the other takes two (start + end).
You've been using overloaded methods since Day 1!

11.3 [Link]() — Heavily Overloaded


StringBuffer sb = new StringBuffer();
[Link]("Hello"); // append(String)
[Link](42); // append(int)
[Link](3.14f); // append(float)
[Link](true); // append(boolean)
[Link]('A'); // append(char)
// All versions share the same name: append

Tip for Interview:


When asked 'Give an example of method overloading that Java itself uses:' say:
1. [Link]() — overloaded for all data types
2. [Link]() — two overloaded versions (1-param and 2-param)
3. [Link]() — overloaded for every data type
Very few candidates give this level of answer. It will immediately impress the interviewer.
12. How to Answer Method Overloading in an Interview
Most candidates give a 10-second definition and stop. The trainer emphasized that a thorough answer
takes 5–10 minutes and covers all of the following points. Writing code on paper or laptop is essential.

Give the complete definition


Step 1 Method Overloading is the process of creating multiple methods with the SAME NAME
within the SAME CLASS, where each method differs in the number or type of
parameters.

Write a code example


Step 2 Create at least 2 overloaded methods. Show the calculator example with add(int,int) and
add(float,float).

Explain the 3 Rules


Step 3 Walk through how the Java Compiler resolves which method to call: (1) Method Name,
(2) Number of Parameters, (3) Type of Parameters.

Explain Type Promotion


Step 4 Explain what happens when no exact match exists. Show the long → float promotion
example with code.

Explain Ambiguity
Step 5 Show the int,int case with add(int,float) and add(float,int). Show the compiler error and
explain why the confusion happens.

Give real-world Java examples


Step 6 Mention [Link](), [Link](), [Link]() as built-in
overloading examples.

Mention all alternative names


Step 7 Compile-Time Polymorphism, False Polymorphism, Static Binding, Early Binding — all
the same concept.

The trainer's message: 'If you answer all 7 steps with code, you will take 5–10 minutes of the interview.
A good interviewer will be fully satisfied. You differentiate yourself from every other candidate who
stops at the definition.'
13. Quick-Reference Summary Table

Concept Details
Definition Multiple methods, same name, same class, different parameters
(number or type)
Who resolves it? Java Compiler (NOT JVM)
When? At Compile Time (before program runs)
Rule 1 Check method name — all matching methods are candidates
Rule 2 Check number of parameters — narrow candidates
Rule 3 Check type of parameters — final selection
Type Promotion When 3 rules fail, compiler widens the type (e.g. long → float)
and retries
Ambiguity When two methods are equally valid after type promotion →
Compile-Time Error
Other names Compile-Time Polymorphism, False Polymorphism, Static
Binding, Early Binding
True vs False False = multiple methods, one name. True = one method, truly
different behavior
Java examples [Link](), [Link](), [Link]()
Return type? Return type alone does NOT distinguish overloaded methods.
Only parameters matter.
14. Interview Q&A — Method Overloading

Q1: What is Method Overloading?

Method Overloading is the process of creating multiple methods with the SAME NAME within the
SAME CLASS, where each method differs in the number or type of parameters. It is resolved by
the Java Compiler at Compile Time. It is also called Compile-Time Polymorphism, False
Polymorphism, Static Binding, and Early Binding.

Q2: What are the 3 rules the Java Compiler uses to resolve method overloading?

Rule 1: Method Name — all methods with the same name are candidates.
Rule 2: Number of Parameters — only methods with the matching parameter count survive.
Rule 3: Type of Parameters — the method whose parameter types match exactly is selected.

Q3: What is Type Promotion in method overloading?

When all 3 rules fail to find an exact match, the Java Compiler automatically promotes (widens)
the passed argument to the next higher compatible data type and tries again. Example: long is
promoted to float if no add(long,long) method exists but add(float,float) does.

Q4: What is Ambiguity in method overloading?

Ambiguity occurs when two or more overloaded methods are equally valid candidates after type
promotion, making it impossible for the compiler to decide. This causes a compile-time error:
'method is ambiguous'. Example: having add(int,float) and add(float,int) and calling add(10,20) —
both become valid via promotion, causing confusion.

Q5: Who resolves method overloading — compiler or JVM?

The Java Compiler resolves method overloading, NOT the JVM. It happens during the
compilation phase, which is why it is called Compile-Time Polymorphism.

Q6: Can method overloading be done by changing only the return type?

NO. You cannot overload methods by changing only the return type. The Java Compiler uses
only the method name and parameter list (number and type) to distinguish overloaded methods.
Return type is irrelevant for overloading and will cause a compile error if you try.

Q7: Give a real-world example of method overloading in Java.

1. [Link]() — overloaded for all data types (int, float, String, char, boolean, long, etc.)
2. [Link]() — overloaded as substring(int start) and substring(int start, int end)
3. [Link]() — overloaded for every primitive and String type
Q8: Why is method overloading called 'False Polymorphism'?

Because it creates the ILLUSION of one method doing many things, when in reality there are
multiple separate methods — one per use case. In method overloading, 8 add() calls go to 8
different methods (8:8 ratio). True polymorphism would mean ONE method actually doing many
things (1:many). So it is false — or an illusion of — polymorphism.

Q9: What is the difference between Static Binding and Dynamic Binding?

Static Binding (Method Overloading): resolved at Compile Time by the Java Compiler. Fixed and
unchanging at runtime.
Dynamic Binding (Method Overriding): resolved at Runtime by the JVM. The actual method
called depends on the object type at runtime.

Q10: What happens if I call an overloaded method with a double value but no double
version exists?

The compiler checks for type promotion. If there is no add(double,double), it checks if double can
be promoted — but double is the highest, so no promotion is possible. The compiler throws a
compile-time error: 'The method add(double, double) is undefined for the type ClassName'.
Final Note from the Trainer
The trainer's closing advice, directly from the class:
• When asked 'Explain Method Overloading' in an interview — do NOT just give the definition.
Write code, explain the 3 rules, show type promotion, show ambiguity, give real-world
examples.
• This one answer, done properly, can fill 5–10 minutes of your technical interview and leave the
interviewer impressed.
• Most engineers say 'multiple methods, same name'. You should say: 'multiple methods, same
name, WITHIN THE SAME CLASS, resolved by the Java Compiler using 3 rules — name,
parameter count, and parameter type — with type promotion when no exact match exists, and
ambiguity when two methods are equally applicable'.
• Knowing type promotion and ambiguity is what separates a hired candidate from a rejected one.
• Two weeks from now, most students forget type promotion and ambiguity. Revise these notes
regularly.

Next Topic
Object Orientation — The Four Pillars of OOP
(Encapsulation, Inheritance, Polymorphism, Abstraction)

These classes will continue for the next 20 days. Attend every class — missing even one session
will make it hard to follow subsequent sessions, as each builds on the previous.

You might also like