The other use of super keyword is to call the super-class constructors from the sub-class constructor. We can change the Ice Cream Prices program discussed in Method Overriding In Java to use the super keyword to call the super-class constructors.

The program discussed in Method Overriding In Java is further changed to use the constructors. We use the super keyword to call the super-class constructor. Since we used constructors, the initialization became simpler and more readable.

THINGS TO TRY

Define a new class BadamMilkWithIceCream which extends from IceCream. Add member variable milliLitersOfBadamMilk and add a method getPrice which calls super.getPrice() to get the price of the ice cream. Create a constructor in this class and call the super-class constructor in it. Assume that the price of milli liter of badam milk is Rs. 0.20.

Exchange the lines LINE A and LINE B and observe the compilation error you get. Please note that when calling the super class constructor, the super keyword should be used only in the first line of the constructor.

One difference between using super keyword to call the super-class methods and using super keyword to call the super-class constructors is that when calling the super-class methods, there is no restriction on where and how many times we can call it, but in case of super-class constructor we can only call it once and it has to be in the first line of the class.