Question 11
Back to Exercise
What is the output of the following Java program?
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!