Unit 3 Cycle 1 Day 12: super Keyword in Constructors
Share
super Keyword in Constructors
Section 3.14 — The super Keyword
Key Concept
When a subclass constructor executes, it must call a superclass constructor as its very first statement using super(arguments). If you do not explicitly call super(), Java automatically inserts a call to the no-argument superclass constructor. If the superclass does not have a no-argument constructor, the subclass must explicitly call a parameterized superclass constructor, or the code will not compile. The AP exam tests constructor chaining across inheritance hierarchies where constructors call super() with specific arguments.
Consider the following classes.
What does new Car(60, 4).getSpeed() return?
Answer: (A) 60
super(s) calls Vehicle's constructor with s=60, setting speed=60. Car inherits getSpeed() from Vehicle, which returns 60.
Why Not the Others?
(B) 4 is the doors value, not speed. getSpeed() returns speed.
(C) The super constructor correctly sets speed to 60.
(D) The code compiles. super(s) correctly calls the parent constructor.
Common Mistake
super() must be the first statement in a subclass constructor. It passes arguments to the parent constructor. Without it, Java tries to call a no-arg parent constructor (which may not exist).
AP Exam Tip
If the parent class has no no-arg constructor, the subclass MUST call super(args) explicitly. Forgetting this causes a compile error.