ProgrammingVery hardProduct company interview · GATE level
Which lines fail to compile?
Which lines fail to compile?
interface I {
static String id() { return "I"; }
default String name() { return "N"; }
}
class C implements I { }
// in main:
C c = new C();
String s1 = I.id(); // L1
String s2 = C.id(); // L2
String s3 = c.name(); // L3
String s4 = c.id(); // L4- A. L4 only
- B. L2 only
- C. L2 and L4
- D. None of them
Correct answer: C. L2 and L4
Static methods of an interface are not inherited by implementing classes (unlike static methods of a superclass), so they can be called only as I.id(). C.id() and c.id() both fail. Default methods are inherited, so c.name() is fine.
More OOP with C++ and Java questions
- What is printed? cpp struct B { virtual string who() const { return "B"; } }; struct D : B { string who() const override { return "D"; }…
- What is printed? cpp struct M { M() { cout << "m"; } ~M() { cout << "~m"; } }; struct B { B() { cout << "b"; f(); } virtual ~B() { cout <<…
- What is printed? cpp struct P { P(const char s) { cout << s; } }; struct B1 { B1() { cout << "1"; } }; struct B2 { B2() { cout << "2"; }…
- What is printed? cpp struct A { A() { } A(const A&) { cout << "C"; } A& operator=(const A&) { cout << "="; return this; } }; void f(A a) {…
- What is printed? cpp struct B { virtual void f() = 0; }; void B::f() { cout << "B"; } struct D : B { void f() override { cout << "D"…
- What is printed? cpp struct C { static int n; C() { n++; } ~C() { n--; } }; int C::n = 0; void f(C c) { } int main() { C a; f(a); f(a); {…