nerdexam
Oracle

1Z0-811 · Question #36

Given: class Bus { String type = "default"; // line n1 Bus (String type) { // line n2 this.type = type; } } public class App{ public static void main(String[] args) { Bus b1 = new Bus()…

The correct answer is C. The code fails to compile. To make it compile, at line n1 insert: Bus() {}. Option C is correct because Java only provides a default no-arg constructor when no constructors are explicitly defined. Since Bus already declares Bus(String type), the compiler removes the implicit no-arg constructor, causing new Bus() in main to fail - and the fix is to…

Object-Oriented Programming Principles

Question

Given: class Bus { String type = "default"; // line n1 Bus (String type) { // line n2 this.type = type; } } public class App{ public static void main(String[] args) { Bus b1 = new Bus(); System.out.println(b1.type); Bus b2 = new Bus("luxury"); System.out.println (b2.type); } } What is the result?

Options

  • AThe code fails to compile. To make it compile, at line n1 insert: this() {}
  • BThe code fails to compile. To make it compile, at line n2 insert: this();
  • CThe code fails to compile. To make it compile, at line n1 insert: Bus() {}
  • DThe code compiles and prints: default luxury

How the community answered

(36 responses)
  • A
    8% (3)
  • B
    3% (1)
  • C
    86% (31)
  • D
    3% (1)

Explanation

Option C is correct because Java only provides a default no-arg constructor when no constructors are explicitly defined. Since Bus already declares Bus(String type), the compiler removes the implicit no-arg constructor, causing new Bus() in main to fail - and the fix is to explicitly declare Bus() {} at line n1.

Option A is wrong because this() {} is not valid constructor declaration syntax; this(...) is a constructor invocation (used to call one constructor from another), not a declaration. Option B is wrong because inserting this() inside the parameterized constructor would attempt to call a no-arg constructor that still doesn't exist, so compilation still fails. Option D is wrong because the code does not compile in its current state - new Bus() has no matching constructor.

Memory tip: Think of it as the compiler's "gift" - it gives you a free no-arg constructor only when you ask for nothing. The moment you define any constructor yourself, the gift is gone and you must provide your own no-arg constructor explicitly if you need one.

Topics

#constructors#default constructor#constructor overloading#object instantiation

Community Discussion

No community discussion yet for this question.

Full 1Z0-811 Practice