ProgrammingHardProduct-company placement · Java
What happens when this class is compiled?
What happens when this class is compiled?
class A {
A() { this(1); }
A(int x) { this(); }
}- A. It compiles; new A() throws StackOverflowError
- B. It compiles; new A() creates an object normally
- C. Compile-time error: recursive constructor invocation
- D. Compile-time error: this() must be the last statement
Correct answer: C. Compile-time error: recursive constructor invocation
The compiler checks this(...) chains and rejects a cycle among constructors, so the class does not compile at all.
More OOP with C++ and Java questions
- What is printed? java class A { void f() { System.out.print("Af "); g(); } void g() { System.out.print("Ag "); } } class B extends A {…
- What is printed? java class Pt { int x; Pt(int x) { this.x = x; } public boolean equals(Object o) { return o instanceof Pt && ((Pt) o).x…
- What is printed? java interface Greeter { String name(); default String greet() { return "Hi " + name(); } } class G implements Greeter {…
- Which line fails to compile? java abstract class Shape { abstract double area(); } // in main: Shape a = new Shape(); // L1 Shape b = new…
- Which lines fail to compile? java class P { void f() { } static void g() { } } class C extends P { static void f() { } // L1 void g() { }…
- Which line fails to compile? java class P { Number get() { return 1; } int size() { return 0; } } class C extends P { Integer get() {…