Task 3 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

7.1 Inheritance — the super constructor

Lesson

Initializing the inherited part

When you create a subclass object, its superclass part must be set up first. The subclass constructor does this by calling super(...) as its first statement, passing whatever arguments the superclass constructor needs.


Worked example

class Dog extends Animal {
    public Dog(String name) {
        super(name);   // runs Animal's constructor to set the inherited name
    }
}

super(name) calls Animal(name), which stores the name. It must come first, before the subclass does anything else.


▶ Try it: run this — new Dog("Buddy") sets the name through super, so getName() returns Buddy.



super(name) in a subclass constructor...


The super(...) call must be...


Type exactly what this program prints.

class Animal { String n; Animal(String x){n=x;} String getName(){return n;} }
class Dog extends Animal { Dog(String x){super(x);} }
public class Main { public static void main(String[] a){
    System.out.println(new Dog("Kai").getName());
}}

super(name) is needed because...


True or false?