LearnFrenzy
Sign in Take a free test

Constructors and the this Keyword · Predict the Output · Question 11

An overridden method called from a parent constructor Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 11 Back to Exercise

What is the output of the following Java program?

Main.java
class Base {
    Base() { describe(); }
    void describe() { System.out.println("Base"); }
}

class Derived extends Base {
    private String name = "Derived";
    Derived() { super(); describe(); }
    @Override void describe() { System.out.println("name=" + name); }
}

public class Main {
    public static void main(String[] args) {
        new Derived();
    }
}
  • A name=null name=Derived Correct
  • B Base name=Derived
  • C name=Derived name=Derived
  • D Base Base
Correct Answer: Option A

Base's constructor runs first and calls the override, but Derived's field initialiser has not run yet, so name is still null. This is why constructors should not call overridable methods.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links