In: Computer Science
Give examples showing how "super" and "this" are useful with inheritance in Java. Include examples of using "super" and "this" both as constructors and as variables.
The example below shows the use of "super" and "this" keyword" as a variable.
The code produces the following output :
Notice that both child class and parent class contained the variable - name of type String. So the variable name of parent class can be accessed only by using keyword - "super". Similarly, "this" keyword is used to access the variable of the same class int the above example.
"super" and "this" as constructor -
Calling one constructor from another constructor is termed as Constructor chaining.
"super" is used to invoke constructor of parent class and "this" is used for invoking some other constructor of same class.
Note that constructor calls should be the first line in constructor to prevent compile time error.
output :
Also, the java compiler automatically invokes the non-paramterized constructor of parent class, whether you insert "super()" as the first line in constructor or not.
"super" keyword used as constructor :
output :