ProgrammingHardHCL · Tech Mahindra pattern

What happens when this is compiled?

What happens when this is compiled?
class A {
    int m() { return 1; }
    double m() { return 1.0; }
}
  1. A. Compiles; two overloads of m() coexist
  2. B. Compile-time error: m() is already defined, methods cannot be overloaded on return type alone
  3. C. Compiles; the second m() overrides the first
  4. D. Compile-time error: only one method per class may be named m

Correct answer: B. Compile-time error: m() is already defined, methods cannot be overloaded on return type alone

Java method signatures consist of the name and parameter types only; return type is not part of the signature. Two methods named m() with identical (empty) parameter lists but different return types is a duplicate-declaration error, not a valid overload.

More OOP with C++ and Java questions

Exams that ask this topic