next up previous
Next: Use of super Up: Unit 03 Previous: Fundamental features of derived

Constructor of a derived class

Let us analyze now how to define constructors in the presence of derivation between classes. Note that a constructor of a derived class must also take care of the construction of the fields of the base class. This can be done by inserting in the constructor of the derived class the call to a constructor of the base class, using the special Java construct super(). The super() statement must appear as the first executable statement in the body of the constructor of the derived class. For example:

public class Student extends Person {
  public Student(String n, String r, String f) {
    super(n,r);  // calls the constructor Person(String,String)
    faculty = f;
  }
  ...
}

The statement super(n,r); calls Person(n,r), which initializes the instance variables name and residence, inherited from the superclass Person, respectively to the strings n and r. Then, the statement faculty = f; assigns to the instance variable faculty the string f.


next up previous
Next: Use of super Up: Unit 03 Previous: Fundamental features of derived