Which statement is true for the following code?

public class Plant {
   private String name;
   public Plant(String name) { this.name = name; }
   public String getName() { return name; }
}

public class Tree extends Plant {
   public void growFruit() { }
   public void dropLeaves() { }
}
  1. The code will compile without changes.

  2. The code will compile if public Tree() { Plant(); } is added to the Tree class.

  3. The code will compile if public Plant() { Tree(); } is added to the Plant class.

  4. The code will compile if public Plant() { this("fern"); } is added to the Plant class.


Correct Option: D
Explanation:

This code defines two classes, Plant and Tree. Tree extends Plant, meaning that it inherits all of the fields and methods of Plant.

The Plant class has a single constructor that takes a String argument and sets the name field to that value. It also has a getter method for the name field.

The Tree class has two methods, growFruit() and dropLeaves(), but no constructors.

Option A) The code will compile without changes. - This is incorrect because the Tree class does not have a constructor, and it needs to call the constructor of the parent class when an instance of Tree is created.

Option B) The code will compile if public Tree() { Plant(); } is added to the Tree class. - This is incorrect because the correct syntax to call the parent constructor is super(), not the name of the parent class.

Option C) The code will compile if public Plant() { Tree(); } is added to the Plant class. - This is incorrect because it does not make sense to call the constructor of a subclass from the constructor of the parent class.

Option D) The code will compile if public Plant() { this("fern"); } is added to the Plant class. - This is correct because it adds a new constructor to the Plant class that takes no arguments and calls another constructor of the same class with a default argument. This allows the Tree class to inherit this constructor and call it with the default argument when an instance of Tree is created.

Therefore, the correct answer is D.

Find more quizzes: