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; }
}- A. Compiles; two overloads of m() coexist
- B. Compile-time error: m() is already defined, methods cannot be overloaded on return type alone
- C. Compiles; the second m() overrides the first
- 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
- What is printed? cpp void f(int p) { cout << "nonconst "; } void f(const int p) { cout << "const "; } int main() { int x = 5; int p = &x…
- Does this compile? java class Outer { private int x = 5; class Inner { void show() { System.out.println(x); } } }
- What is printed? cpp struct Base { virtual void f() { cout << "Base"; } }; struct Derived : Base { void f() { cout << "Derived"; } }; int…
- What is printed? java class Picker { static void f(int a, int b) { System.out.print("fixed"); } static void f(int... a) {…
- What happens when this is compiled? cpp struct Base final { virtual void f() { cout << "Base"; } }; struct Derived : Base { };
- What is printed? cpp struct Base {}; struct Derived : Base {}; void f(Base b) { cout << "Base"; } void f(Derived d) { cout << "Derived"; }…