ProgrammingVery hardAmazon/Microsoft SDE MCQ · Java placement
What is printed?
What is printed?
interface I { default String n() { return "I"; } }
class P { public String n() { return "P"; } }
class C extends P implements I { }
// in main:
System.out.print(new C().n());- A. I
- B. PI
- C. P
- D. Compile error: C must override n()
Correct answer: C. P
When a class inherits a method from its superclass and a default method from an interface, the class method wins ("class wins" rule), so no override is needed and P's n() runs. A conflict only arises between two interfaces' defaults.
More OOP with C++ and Java questions
- What is printed (C++17)? cpp struct T { T() { } T(const T&) { cout << "C"; } T(T&&) { cout << "M"; } }; int main() { const T a; T b =…
- What is printed? cpp struct T { T() { } T(const T&) { cout << "C"; } }; struct W { T t; }; int main() { W a; W b = std::move(a); }
- What is printed? cpp struct A { virtual void f() = 0; }; void A::f() { cout << "A"; } struct B : A { void f() override { A::f(); cout <<…
- What is printed? cpp struct B { virtual ~B() { } }; struct D1 : B { }; struct D2 : B { }; int main() { B p = new D1; cout <<…
- What is printed? cpp struct B { }; // no virtual functions struct D : B { }; struct VB { virtual ~VB() { } }; struct VD : VB { }; int…
- What is printed (C++17)? cpp int main() { int x = 0; auto f = [x]() mutable { return ++x; }; f(); auto g = f; f(); cout << f() << g() <<…