2.6 Constructors in Derived Classes2.5 Interface Hierarchies2 Java with Caffeine2.7 Code Sharing

2.6 Constructors in Derived Classes

As shown in above example, each class has its own constructors, e.g.

   class Article
   {
     int number;
     String title;
     int price;

     Article(int n, String t, int p) 
     { 
        number = n; 
        title = t;
        price = p;
     }
   }

   class Book extends Article
   {
     String author;
     String publisher;
     String ISBN;

     Book(int n, String t, int p, String a, String pb, String i) 
     {
        number = n;
        title = t;
        price = p;
        author = a;
        publisher = pb;
        ISBN = i;
     }
   }

Please note that class Book inherits all the fields of Article, therefore its constructor must also initialize these fields in addition to the fields declared locally. However, above solution is rather clumsy because it duplicates the code of the Article constructor. It would be better if the Book constructor could call the Article constructor.

Java allows a constructor to call a constructor of the base class by a statement

   super(...);

as the first statement of the constructor body (like we can write this(...) to call another constructor of class Book).

Above class can therefore be rewritten as

   class Book extends Article
   {
     String author;
     String publisher;
     String ISBN;

     Book(int n, String t, int p, String a, String pb, String i) 
     {
        super(n, t, p);
        author = a;
        publisher = pb;
        ISBN = i;
     }
   }

The constructor now calls the Article constructor to initialize the fields declared in Article and itself initializes only those fields declared in Book.

Above example describes the typical form of the initialization of objects of derived classes. A constructor only cares for the fields declared locally in its class and delegates the initialization of the fields of the superclass to the constructor of this class. If there is no call to a constructor of the superclass, then the compiler automatically inserts a call

   super();

to the default constructor of the superclass. In this case, the superclass must explicitly contain such a constructor without parameters (the implicitly generated default constructor does not suffice).


© Wolfgang Schreiner; February 3, 2005

2.6 Constructors in Derived Classes2.5 Interface Hierarchies2 Java with Caffeine2.7 Code Sharing