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.
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)- A8% (2)
- B4% (1)
- C4% (1)
- D85% (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.
This option is incorrect because the presence of multiple methods with the same name and parameter signature prevents the code from compiling.
This option is incorrect as the code will not compile due to ambiguous method definitions, not execute any specific method.
This option is incorrect because the Java compiler will flag an error due to the invalid method overloading before runtime.
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
Community Discussion
No community discussion yet for this question.