nerdexam
Oracle

1Z0-803 · Question #85

Given: class Overloading { int x(double d) { System.out.println("one"); return 0; } String x(double d) { System.out.println("two"); return null; } double x(double d) { System.out.println("three"); ret

The correct answer is D. Compilation fails.. Java's method overloading requires methods with the same name to have different parameter lists; merely having different return types for methods with identical parameter lists leads to a compilation error.

Working with Methods and Encapsulation

Question

Given:

class Overloading { int x(double d) { System.out.println("one"); return 0; } String x(double d) { System.out.println("two"); return null; } double x(double d) { System.out.println("three"); return 0.0; } public static void main(String[] args) { new Overloading().x(4.0); } } What is the result?

Options

  • Aone
  • Btwo
  • Cthree
  • DCompilation fails.

How the community answered

(26 responses)
  • A
    8% (2)
  • B
    4% (1)
  • C
    4% (1)
  • D
    85% (22)

Why each option

Java's method overloading requires methods with the same name to have different parameter lists; merely having different return types for methods with identical parameter lists leads to a compilation error.

Aone

This option is incorrect because the presence of multiple methods with the same name and parameter signature prevents the code from compiling.

Btwo

This option is incorrect as the code will not compile due to ambiguous method definitions, not execute any specific method.

Cthree

This option is incorrect because the Java compiler will flag an error due to the invalid method overloading before runtime.

DCompilation fails.Correct

Compilation fails because the `Overloading` class defines three methods all named `x` with the exact same parameter list (`double d`). Java's method overloading rules state that methods must have distinct parameter signatures (number, type, or order of parameters); differing return types alone are not sufficient to distinguish overloaded methods, resulting in a 'method x(double) is already defined' error.

Concept tested: Java method overloading rules, compilation errors

Source: https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html

Topics

#method overloading#method signature#compilation errors

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice