← Back to quizzesFree quiz

Java Polymorphism and Overloading

Method overloading is a core feature of Java that allows a class to have multiple methods with the same name but different parameter lists . This capability enables developers to write more…

16 questions~8 min
Java Polymorphism and Overloading — Qwi
0 / 16
Score: 0%
1

When a class defines two methods with the same name but different parameter lists, what Java mechanism determines which method is executed at compile time?

2

Given the class Calculator with overloaded add methods, which call will invoke the double version of add?

3

If a call to show(shortVar) matches both show(int) and show(double) overloads, which method is selected and why?

4

What is the primary difference between overloading and overriding in Java?

5

In class Car, the constructor Car(String model) attempts to call another constructor with this((model, 4));. Assuming correct syntax, what is the purpose of this call?

6

Why is the following method call illegal? myPrint(5.0) where myPrint is defined as void myPrint(int i).

7

Consider class Student with three constructors. Which constructor call will set regNo to its default value while providing a name?

8

Which of the following statements about Java method signatures is FALSE?

9

When a subclass constructor does not explicitly call super(...), what happens first?

10

In the widening chain, which conversion is NOT allowed implicitly?

11

What is the main advantage of overloading constructors as shown in the Student class?

12

If a class defines both void debug() and void debug(String s), which method is called by debug("test")?

13

Which statement best describes Java's handling of overloaded methods when no exact match exists for the argument types?

14

In the Vehicle/Car example, which constructor of Car will be executed when creating new Car("Sedan")?

15

Why does the overloaded print method in Java appear to 'print anything'?

16

Which of the following best explains why overloading is considered an 'illusion' according to the lecture notes?

Understanding Java Method Overloading

Method overloading is a core feature of Java that allows a class to have multiple methods with the same name but different parameter lists. This capability enables developers to write more readable code and to provide intuitive variations of a method for different data types.

Compile‑time Resolution

When the compiler encounters a call to an overloaded method, it must decide which version to invoke. This decision is made entirely at compile time using the method overloading resolution algorithm, which examines the number, type, and order of the arguments.

  • Exact match: The compiler prefers a method whose parameters exactly match the argument types.
  • Widening conversion: If an exact match is not available, the compiler may widen primitive types (e.g., int to long).
  • Boxing/unboxing: Autoboxing can be applied as a last resort (e.g., int to Integer).
  • Varargs: A var‑args method is considered only after all other candidates are exhausted.

Because the selection occurs before the program runs, the chosen method cannot be changed based on the object's runtime type. This is why overloading is sometimes described as static polymorphism.

Practical Overloading Examples

Choosing the Double Overload

Consider a Calculator class with several add methods:

public int add(int a, int b) { return a + b; }
public double add(int a, double b) { return a + b; }
public double add(double a, double b) { return a + b; }

Which call invokes the double version?

  • Correct: add(2, 3.0) – the presence of a double argument forces the compiler to select the overload that includes a double parameter.
  • Incorrect: add(2, 3, 4) – no matching signature.
  • Incorrect: add(2.0, 3) – matches add(double, double) after widening int to double, but the original call with a double as the second argument is a clearer match.
  • Incorrect: add(2, 3) – both arguments are int, so the int overload is chosen.

Key Takeaways

  • Method overload resolution picks the most specific match for the argument types.
  • A double argument forces the compiler to choose the overload that includes a double parameter.
  • When one argument is an int and the other a double, the double overload is the best fit.

How to Remember

  • Mnemonic: “Double‑Down on Doubles” – if a call has a double, the double method wins.
  • Tip: Look at the argument types; the presence of a double signals the double‑parameter overload.

Widening vs. Narrowing in Overload Selection

Short to Int vs. Double

Suppose you have two overloads: show(int) and show(double). When you call show(shortVar), the compiler must decide which method to use.

  • Correct answer: show(int) because the short can be widened to int with a single conversion, whereas converting to double would require an additional widening step.
  • The rule is that the compiler prefers the *least* amount of conversion.

This example illustrates how Java’s overload resolution favors the *closest* primitive type.

Overloading vs. Overriding

Although both concepts are often grouped under the term “polymorphism,” they serve different purposes.

Key Differences

  • Signature: Overloading uses different method signatures (parameter lists) within the same class, while overriding keeps the exact same signature in a subclass.
  • Inheritance: Overloading does not require inheritance; it can occur entirely within a single class. Overriding, by definition, involves a superclass‑subclass relationship.
  • Timing: Overloading is resolved at compile time; overriding is resolved at runtime via dynamic dispatch.

Understanding this distinction helps you decide when to use each technique. Use overloading to provide convenient variations of a method, and use overriding to change behavior in a subclass.

Constructor Chaining with this()

Java allows one constructor to call another constructor in the same class using the this(...) syntax. This technique, called constructor chaining, reduces code duplication.

Example: Car Class

public class Car {
    private String model;
    private int doors;

    public Car(String model, int doors) {
        this.model = model;
        this.doors = doors;
    }

    public Car(String model) {
        this(model, 4); // Calls the two‑parameter constructor
    }
}

In the second constructor, this(model, 4) delegates the initialization to the primary constructor, ensuring that both fields are set consistently.

Purpose: To initialize the model field and set doors to 4 using the two‑parameter constructor.

Illegal Method Calls and Narrowing Conversions

Java permits primitive widening (e.g., int → long) but disallows implicit narrowing (e.g., double → int) without an explicit cast.

Why myPrint(5.0) is Illegal

If myPrint is declared as void myPrint(int i), the call myPrint(5.0) attempts to pass a double where an int is expected. Since this requires a narrowing conversion, the compiler rejects the call unless you explicitly cast the argument: myPrint((int)5.0).

Takeaway: Java cannot perform a narrowing conversion without an explicit cast.

Choosing the Right Constructor

When a class defines multiple constructors, each signature determines which fields are initialized directly and which receive default values.

Student Class Example

public class Student {
    private String name;
    private int regNo;

    public Student() { /* defaults */ }
    public Student(String name) { this.name = name; }
    public Student(String name, int regNo) { this.name = name; this.regNo = regNo; }
}

To set only the name while leaving regNo at its default (e.g., 0), you would use:

new Student("Alice");

Key Takeaways

  • When a constructor omits a parameter, that field gets its default value.
  • Providing only the name argument means the registration number is not set, so it stays at its default (e.g., 0 or null).
  • Choosing the constructor that matches the desired arguments avoids unnecessary placeholder values.

How to Remember

  • Mnemonic: “Name‑Only → No Number” – if you give just a name, the number defaults.
  • Tip: Match the constructor signature to the data you actually have; missing fields automatically revert to defaults.

Method Signatures in Java

A method signature in Java consists of the method name and the ordered list of parameter types. The return type, access modifiers, and exceptions are not part of the signature.

Common Misconception

Which statement about method signatures is FALSE?

  • Methods with identical parameter lists cannot coexist in the same class – true.
  • Two methods can share the same name if their parameter types differ – true.
  • The return type is part of the method signature in Java – false. Java does not consider return type when distinguishing overloads.
  • Parameter order matters for distinguishing signatures – true.

Understanding the exact composition of a signature prevents compile‑time errors and helps you design clean, overload‑friendly APIs.

SEO‑Optimized Summary

Mastering Java method overloading, constructor chaining, and the nuances of method signatures empowers developers to write cleaner, more maintainable code. By focusing on compile‑time resolution, proper use of this(), and the distinction between overloading and overriding, you can avoid common pitfalls such as illegal narrowing conversions and ambiguous overloads.

Keywords: Java method overloading, compile‑time resolution, constructor chaining, this(), method signatures, overloading vs overriding, primitive widening, narrowing conversion.