ProgrammingVery hardProduct-company placement · GATE CS
What is printed?
What is printed?
class A {
void f(Object o) { System.out.print("AO "); }
void f(String s) { System.out.print("AS "); }
}
class B extends A {
void f(Object o) { System.out.print("BO "); }
}
// in main:
A x = new B();
x.f("hi");
x.f((Object) "hi");- A. BO BO
- B. AS BO
- C. AS AO
- D. BO AS
Correct answer: B. AS BO
The overload is chosen at compile time from the argument's static type: f(String) for "hi" and f(Object) for the cast. Only then does overriding pick the run-time class's version: B overrides f(Object) but not f(String), giving AS then BO.
More OOP with C++ and Java questions
- What is printed? java class P { String n = "P"; String get() { return n; } } class C extends P { String n = "C"; String get() { return n…
- What is printed? java class P { P() { show(); } void show() { System.out.print("P "); } } class C extends P { int x = 5; final int y = 7…
- What is printed? java static int f() { int x = 1; try { return x; } finally { x = 2; } } static StringBuilder g() { StringBuilder sb = new…
- What is printed? java static void m(StringBuilder a, StringBuilder b) { a.append("1"); b = a; b.append("2"); } // in main: StringBuilder x…
- What is printed? java char c = 'a'; c += 1; System.out.print(c + 1); System.out.print(" " + c + 1);
- Which statement about this code is correct? java Object[] arr = new String[2]; // L1 arr[0] = "a"; // L2 arr[1] = Integer.valueOf(1); //…