Super-class constructors cannot be overridden as the constructors have the same name as their class. To be able to access a constructor in a sub-class with the same number and data type of arguments as in the super-class, it must be defined in the sub-class itself. When constructors are defined in a sub-class, the corresponding super-class constructors are called during the creation of objects of that sub-class. This ensures that the initialization of inherited parts of the objects takes place similar to the way the super-class initializes its objects. Thus, defining constructors explicitly in the sub-class will override or overload super-class constructors.
Generally, super-class methods are called using the following syntax:
This syntax cannot be used in the case of constructors, as constructors do not have a method name. The constructors of the super-class are called without having method name as shown below:
Java follows specific rules for the use of keyword super()
1. The first calling method must be super() in the constructor's definition. If the super()
method is not specified, Java will implicitly call the super() method with no arguments.
2. Super() is used to call a constructor method with the appropriate arguments from the immediate super-class. This may, in turn, call the constructor of its super-class and so on. The usage of super() in the constructor is similar to the use of keyword this().
3. To use super() in the constructor of sub-class, a constructor with the same signature must exist in the super-class.
A constructor in the super-class with exactly the same signature as the constructor in the sub-class need not be called from the sub-class. Only those constructors for which values need to be initialized in the sub-class should be called. The programmer can therefore simply create sub-classes that have constructors with entirely different signatures from any of the super-class constructors. Program illustrates how this can be done.
Using constructors with different signatures in the sub-class and super-class.
this.num = n;
System.out.println ("num" +num);
class Two extends one
Two(int x, int y)
num1 = y;
System.out.println("sub class number"+num1);
System.out.println("super class number"+num);
public static void main(String args[ ])
Two t = new Two(100,200);
The output of SampleClass program is as shown below:
sub class number 200
super class number 100
Program defines a class SimpleClass. It creates an object of class Two which extends the class One. The class One has only one constructor, which assigns the value of n to num. The class Two has an additional instance variable (y in this example) and defines a constructor to initialize x and y. The constructor defined in the program calls the constructor method belonging to class One to initialize the instance variable x of class Two.