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.**
Below we have implemented program to demonstrate use of "super" and "this" keywords in java and how they play a role in inheritance of classes.
Some important points about "super" and "this" :
Using Super in constructor:
Code:
public class Parent { // Parent class constructor public Parent() { System.out.println("Parent class constructor"); } } class Child extends Parent{ public Child(){ // Calling parent class constructor super(); System.out.println("From parent to child constructor"); } // Main() public static void main(String[] args) { // Creating child class object Child c = new Child(); } }
Output:
Using super to access parent class variables:
Code:
public class Parent { // Parent class variables String var = "Hell0"; int num = 25; // Parent class constructor public Parent() { System.out.println("Parent class constructor"); } } class Child extends Parent{ public Child(){ // Calling parent class constructor super(); System.out.println("From parent to child constructor"); } public void printItems(){ // Printing parent class variables using super System.out.println(super.var + " " + super.num); } // Main() public static void main(String[] args) { // Creating child class object Child c = new Child(); c.printItems(); } }
Output:
Using this keyword to call constructors of the same class, and using this to assign values of the current class:
Code:
public class Parent { // Parent class variables private String var; private int num; // Parent class constructor public Parent() { // Using this key word to call parameterised constructor of this class this("Parent", 25); System.out.println("Parent class constructor"); } public Parent(String var, int num) { // Using this key word to assign values to the variables of this class this.var = var; this.num = num; } public void print(){ System.out.println(var + " " + num); } } class Child extends Parent { private String var; private int num; public Child() { // Calling Parent default constructor super(); } public Child(String var, int num) { // Calling parent class constructor and passing attributes super(var, num); System.out.println("From parent to child constructor"); } @Override public void print() { // Calling Parent class method using super super.print(); } // Main() public static void main(String[] args) { // Creating child class object Child c = new Child("Child", 10); c.print(); Child c2 = new Child(); c2.print(); } }
Output:
#Please ask for any doubts. Thanks.